Merge pull request #263 from YunoHost/unify-loggers

[fix] Logging
This commit is contained in:
Alexandre Aubin 2021-02-28 17:33:24 +01:00 committed by GitHub
commit cb5b8c74ec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 28 additions and 14 deletions

View file

@ -90,12 +90,12 @@ def api(host="localhost", port=80, routes={}):
except MoulinetteError as e: except MoulinetteError as e:
import logging import logging
logging.getLogger(logging.main_logger).error(e.strerror) logging.getLogger("moulinette").error(e.strerror)
return 1 return 1
except KeyboardInterrupt: except KeyboardInterrupt:
import logging import logging
logging.getLogger(logging.main_logger).info(m18n.g("operation_interrupted")) logging.getLogger("moulinette").info(m18n.g("operation_interrupted"))
return 0 return 0
@ -122,7 +122,7 @@ def cli(args, top_parser, output_as=None, timeout=None):
except MoulinetteError as e: except MoulinetteError as e:
import logging import logging
logging.getLogger(logging.main_logger).error(e.strerror) logging.getLogger("moulinette").error(e.strerror)
return 1 return 1
return 0 return 0

View file

@ -577,14 +577,14 @@ class ActionsMap(object):
log_id = start_action_logging() log_id = start_action_logging()
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
# Log arguments in debug mode only for safety reasons # Log arguments in debug mode only for safety reasons
logger.info( logger.debug(
"processing action [%s]: %s with args=%s", "processing action [%s]: %s with args=%s",
log_id, log_id,
full_action_name, full_action_name,
arguments, arguments,
) )
else: else:
logger.info("processing action [%s]: %s", log_id, full_action_name) logger.debug("processing action [%s]: %s", log_id, full_action_name)
# Load translation and process the action # Load translation and process the action
m18n.load_namespace(namespace) m18n.load_namespace(namespace)

View file

@ -39,7 +39,11 @@ class Translator(object):
# Attempt to load default translations # Attempt to load default translations
if not self._load_translations(default_locale): if not self._load_translations(default_locale):
logger.error( logger.error(
"unable to load locale '%s' from '%s'", default_locale, locale_dir "unable to load locale '%s' from '%s'. Does the file '%s/%s.json' exists?",
default_locale,
locale_dir,
locale_dir,
default_locale,
) )
self.default_locale = default_locale self.default_locale = default_locale
@ -82,6 +86,9 @@ class Translator(object):
self.locale = locale self.locale = locale
return True return True
def key_exists(self, key):
return key in self._translations[self.default_locale]
def translate(self, key, *args, **kwargs): def translate(self, key, *args, **kwargs):
"""Retrieve proper translation for a key """Retrieve proper translation for a key
@ -96,7 +103,7 @@ class Translator(object):
if key in self._translations.get(self.locale, {}): if key in self._translations.get(self.locale, {}):
try: try:
return self._translations[self.locale][key].format(*args, **kwargs) return self._translations[self.locale][key].format(*args, **kwargs)
except KeyError as e: except Exception as e:
unformatted_string = self._translations[self.locale][key] unformatted_string = self._translations[self.locale][key]
error_message = ( error_message = (
"Failed to format translated string '%s': '%s' with arguments '%s' and '%s, raising error: %s(%s) (don't panic this is just a warning)" "Failed to format translated string '%s': '%s' with arguments '%s' and '%s, raising error: %s(%s) (don't panic this is just a warning)"
@ -104,7 +111,7 @@ class Translator(object):
) )
if not during_unittests_run(): if not during_unittests_run():
logger.exception(error_message) logger.warning(error_message)
else: else:
raise Exception(error_message) raise Exception(error_message)
@ -114,20 +121,19 @@ class Translator(object):
self.default_locale != self.locale self.default_locale != self.locale
and key in self._translations.get(self.default_locale, {}) and key in self._translations.get(self.default_locale, {})
): ):
logger.info("untranslated key '%s' for locale '%s'", key, self.locale)
try: try:
return self._translations[self.default_locale][key].format( return self._translations[self.default_locale][key].format(
*args, **kwargs *args, **kwargs
) )
except KeyError as e: except Exception as e:
unformatted_string = self._translations[self.default_locale][key] unformatted_string = self._translations[self.default_locale][key]
error_message = ( error_message = (
"Failed to format translatable string '%s': '%s' with arguments '%s' and '%s', raising error: %s(%s) (don't panic this is just a warning)" "Failed to format translatable string '%s': '%s' with arguments '%s' and '%s', raising error: %s(%s) (don't panic this is just a warning)"
% (key, unformatted_string, args, kwargs, e.__class__.__name__, e) % (key, unformatted_string, args, kwargs, e.__class__.__name__, e)
) )
if not during_unittests_run(): if not during_unittests_run():
logger.exception(error_message) logger.warning(error_message)
else: else:
raise Exception(error_message) raise Exception(error_message)
@ -139,7 +145,7 @@ class Translator(object):
) )
if not during_unittests_run(): if not during_unittests_run():
logger.exception(error_message) logger.warning(error_message)
else: else:
raise Exception(error_message) raise Exception(error_message)
@ -254,6 +260,15 @@ class Moulinette18n(object):
""" """
return self._namespaces[self._current_namespace].translate(key, *args, **kwargs) return self._namespaces[self._current_namespace].translate(key, *args, **kwargs)
def key_exists(self, key):
"""Check if a key exists in the translation files
Keyword arguments:
- key -- The key to translate
"""
return self._namespaces[self._current_namespace].key_exists(key)
class MoulinetteSignals(object): class MoulinetteSignals(object):

View file

@ -208,7 +208,7 @@ class _HTTPArgumentParser(object):
def _error(self, message): def _error(self, message):
# TODO: Raise a proper exception # TODO: Raise a proper exception
raise MoulinetteError(message) raise MoulinetteError(message, raw_msg=True)
class _ActionsMapPlugin(object): class _ActionsMapPlugin(object):

View file

@ -65,7 +65,6 @@ def configure_logging(logging_config=None):
# load configuration from dict # load configuration from dict
dictConfig(DEFAULT_LOGGING) dictConfig(DEFAULT_LOGGING)
if logging_config: if logging_config:
logging.main_logger = logging_config.get("main_logger")
dictConfig(logging_config) dictConfig(logging_config)