1
0
mirror of https://github.com/janeczku/calibre-web synced 2024-11-28 12:30:00 +00:00

Refactored exception logging

This commit is contained in:
Ozzieisaacs 2020-12-12 08:11:00 +01:00
parent 1ae778d81e
commit b637a63e71
10 changed files with 27 additions and 51 deletions

View File

@ -765,5 +765,5 @@ def lcase(s):
return unidecode.unidecode(s.lower()) return unidecode.unidecode(s.lower())
except Exception as e: except Exception as e:
log = logger.create() log = logger.create()
log.exception(e) log.debug_or_exception(e)
return s.lower() return s.lower()

View File

@ -259,10 +259,7 @@ def delete_book(book_id, book_format, jsonResponse):
filter(db.Data.format == book_format).delete() filter(db.Data.format == book_format).delete()
calibre_db.session.commit() calibre_db.session.commit()
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
calibre_db.session.rollback() calibre_db.session.rollback()
else: else:
# book not found # book not found
@ -719,7 +716,7 @@ def edit_book(book_id):
flash(error, category="error") flash(error, category="error")
return render_edit_book(book_id) return render_edit_book(book_id)
except Exception as e: except Exception as e:
log.exception(e) log.debug_or_exception(e)
calibre_db.session.rollback() calibre_db.session.rollback()
flash(_("Error editing book, please check logfile for details"), category="error") flash(_("Error editing book, please check logfile for details"), category="error")
return redirect(url_for('web.show_book', book_id=book.id)) return redirect(url_for('web.show_book', book_id=book.id))

View File

@ -156,8 +156,5 @@ def on_received_watch_confirmation():
move(os.path.join(tmp_dir, "tmp_metadata.db"), dbpath) move(os.path.join(tmp_dir, "tmp_metadata.db"), dbpath)
calibre_db.reconnect_db(config, ub.app_DB_path) calibre_db.reconnect_db(config, ub.app_DB_path)
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
return '' return ''

View File

@ -199,10 +199,7 @@ def getDrive(drive=None, gauth=None):
except RefreshError as e: except RefreshError as e:
log.error("Google Drive error: %s", e) log.error("Google Drive error: %s", e)
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
else: else:
# Initialize the saved creds # Initialize the saved creds
gauth.Authorize() gauth.Authorize()

View File

@ -562,10 +562,7 @@ def get_book_cover_internal(book, use_generic_cover_on_failure):
log.error('%s/cover.jpg not found on Google Drive', book.path) log.error('%s/cover.jpg not found on Google Drive', book.path)
return get_cover_on_failure(use_generic_cover_on_failure) return get_cover_on_failure(use_generic_cover_on_failure)
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
return get_cover_on_failure(use_generic_cover_on_failure) return get_cover_on_failure(use_generic_cover_on_failure)
else: else:
cover_file_path = os.path.join(config.config_calibre_dir, book.path) cover_file_path = os.path.join(config.config_calibre_dir, book.path)
@ -697,7 +694,7 @@ def check_unrar(unrarLocation):
log.debug("unrar version %s", version) log.debug("unrar version %s", version)
break break
except (OSError, UnicodeDecodeError) as err: except (OSError, UnicodeDecodeError) as err:
log.exception(err) log.debug_or_exception(err)
return _('Error excecuting UnRar') return _('Error excecuting UnRar')

View File

@ -41,10 +41,18 @@ logging.addLevelName(logging.WARNING, "WARN")
logging.addLevelName(logging.CRITICAL, "CRIT") logging.addLevelName(logging.CRITICAL, "CRIT")
class _Logger(logging.Logger):
def debug_or_exception(self, message, *args, **kwargs):
if is_debug_enabled():
self.exception(message, stacklevel=2, *args, **kwargs)
else:
self.error(message, stacklevel=2, *args, **kwargs)
def get(name=None): def get(name=None):
return logging.getLogger(name) return logging.getLogger(name)
def create(): def create():
parent_frame = inspect.stack(0)[1] parent_frame = inspect.stack(0)[1]
if hasattr(parent_frame, 'frame'): if hasattr(parent_frame, 'frame'):
@ -54,7 +62,6 @@ def create():
parent_module = inspect.getmodule(parent_frame) parent_module = inspect.getmodule(parent_frame)
return get(parent_module.__name__) return get(parent_module.__name__)
def is_debug_enabled(): def is_debug_enabled():
return logging.root.level <= logging.DEBUG return logging.root.level <= logging.DEBUG
@ -99,6 +106,7 @@ def setup(log_file, log_level=None):
May be called multiple times. May be called multiple times.
''' '''
log_level = log_level or DEFAULT_LOG_LEVEL log_level = log_level or DEFAULT_LOG_LEVEL
logging.setLoggerClass(_Logger)
logging.getLogger(__package__).setLevel(log_level) logging.getLogger(__package__).setLevel(log_level)
r = logging.root r = logging.root

View File

@ -88,10 +88,7 @@ def register_user_with_oauth(user=None):
try: try:
ub.session.commit() ub.session.commit()
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
ub.session.rollback() ub.session.rollback()
@ -210,10 +207,7 @@ if ub.oauth_support:
ub.session.add(oauth_entry) ub.session.add(oauth_entry)
ub.session.commit() ub.session.commit()
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
ub.session.rollback() ub.session.rollback()
# Disable Flask-Dance's default behavior for saving the OAuth token # Disable Flask-Dance's default behavior for saving the OAuth token
@ -245,10 +239,7 @@ if ub.oauth_support:
flash(_(u"Link to %(oauth)s Succeeded", oauth=provider_name), category="success") flash(_(u"Link to %(oauth)s Succeeded", oauth=provider_name), category="success")
return redirect(url_for('web.profile')) return redirect(url_for('web.profile'))
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
ub.session.rollback() ub.session.rollback()
else: else:
flash(_(u"Login failed, No User Linked With OAuth Account"), category="error") flash(_(u"Login failed, No User Linked With OAuth Account"), category="error")
@ -295,10 +286,7 @@ if ub.oauth_support:
logout_oauth_user() logout_oauth_user()
flash(_(u"Unlink to %(oauth)s Succeeded", oauth=oauth_check[provider]), category="success") flash(_(u"Unlink to %(oauth)s Succeeded", oauth=oauth_check[provider]), category="success")
except Exception as e: except Exception as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
ub.session.rollback() ub.session.rollback()
flash(_(u"Unlink to %(oauth)s Failed", oauth=oauth_check[provider]), category="error") flash(_(u"Unlink to %(oauth)s Failed", oauth=oauth_check[provider]), category="error")
except NoResultFound: except NoResultFound:

View File

@ -161,8 +161,7 @@ class CalibreTask:
self.run(*args) self.run(*args)
except Exception as e: except Exception as e:
self._handleError(str(e)) self._handleError(str(e))
if logger.is_debug_enabled(): log.debug_or_exception(e)
log.exception(e)
self.end_time = datetime.now() self.end_time = datetime.now()
@ -211,7 +210,6 @@ class CalibreTask:
self._progress = x self._progress = x
def _handleError(self, error_message): def _handleError(self, error_message):
log.error(error_message)
self.stat = STAT_FAIL self.stat = STAT_FAIL
self.progress = 1 self.progress = 1
self.error = error_message self.error = error_message

View File

@ -167,7 +167,7 @@ class TaskEmail(CalibreTask):
smtplib.stderr = org_smtpstderr smtplib.stderr = org_smtpstderr
except (MemoryError) as e: except (MemoryError) as e:
log.exception(e) log.debug_or_exception(e)
self._handleError(u'MemoryError sending email: ' + str(e)) self._handleError(u'MemoryError sending email: ' + str(e))
# return None # return None
except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e: except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
@ -178,7 +178,7 @@ class TaskEmail(CalibreTask):
elif hasattr(e, "args"): elif hasattr(e, "args"):
text = '\n'.join(e.args) text = '\n'.join(e.args)
else: else:
log.exception(e) log.debug_or_exception(e)
text = '' text = ''
self._handleError(u'Smtplib Error sending email: ' + text) self._handleError(u'Smtplib Error sending email: ' + text)
# return None # return None
@ -225,7 +225,7 @@ class TaskEmail(CalibreTask):
data = file_.read() data = file_.read()
file_.close() file_.close()
except IOError as e: except IOError as e:
log.exception(e) log.debug_or_exception(e)
log.error(u'The requested file could not be read. Maybe wrong permissions?') log.error(u'The requested file could not be read. Maybe wrong permissions?')
return None return None

View File

@ -316,10 +316,7 @@ def import_ldap_users():
try: try:
new_users = services.ldap.get_group_members(config.config_ldap_group_name) new_users = services.ldap.get_group_members(config.config_ldap_group_name)
except (services.ldap.LDAPException, TypeError, AttributeError, KeyError) as e: except (services.ldap.LDAPException, TypeError, AttributeError, KeyError) as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
showtext['text'] = _(u'Error: %(ldaperror)s', ldaperror=e) showtext['text'] = _(u'Error: %(ldaperror)s', ldaperror=e)
return json.dumps(showtext) return json.dumps(showtext)
if not new_users: if not new_users:
@ -347,10 +344,7 @@ def import_ldap_users():
try: try:
user_data = services.ldap.get_object_details(user=user_identifier, query_filter=query_filter) user_data = services.ldap.get_object_details(user=user_identifier, query_filter=query_filter)
except AttributeError as e: except AttributeError as e:
if config.config_log_level == logger.logging.DEBUG: log.debug_or_exception(e)
log.exception(e)
else:
log.error(e)
continue continue
if user_data: if user_data:
user_login_field = extract_dynamic_field_from_filter(user, config.config_ldap_user_object) user_login_field = extract_dynamic_field_from_filter(user, config.config_ldap_user_object)