diff --git a/pysegcnn/core/logging.py b/pysegcnn/core/logging.py index c7c646433d67bae447fa4530561f1805e11e469c..8d8a720b29603386e871315a00bae9722c2f877f 100644 --- a/pysegcnn/core/logging.py +++ b/pysegcnn/core/logging.py @@ -18,8 +18,38 @@ License import pathlib +# logging configuration dictionary +LOGGING_CONFIG = { + 'version': 1, + 'disable_existing_loggers': False, + 'formatters': { + 'brief': { + 'format': '%(name)s: %(message)s' + }, + 'standard': { + 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', + 'datefmt': '%Y-%m-%dT%H:%M:%S' + }, + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'formatter': 'brief', + 'level': 'INFO', + 'stream': 'ext://sys.stderr', + }, + }, + 'loggers': { + '': { + 'handlers': ['console'], + 'level': 'INFO', + }, + } +} + + # the logging configuration dictionary -def log_conf(logfile): +def log_conf(logfile=None): """Set basic logging configuration. See the logging `docs`_ for a detailed description of the configuration @@ -31,7 +61,8 @@ def log_conf(logfile): Parameters ---------- logfile : `str` or :py:class:`pathlib.Path` - The file to save the logs to. + The file to save the logs to. The default is `None`, which means only + log to stdout and not to file. Returns ------- @@ -40,44 +71,19 @@ def log_conf(logfile): """ # check if the parent directory of the log file exists - logfile = pathlib.Path(logfile) - if not logfile.parent.is_dir(): - logfile.parent.mkdir(parents=True, exist_ok=True) - - LOGGING_CONFIG = { - 'version': 1, - 'disable_existing_loggers': False, - 'formatters': { - 'brief': { - 'format': '%(name)s: %(message)s' - }, - 'standard': { - 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', - 'datefmt': '%Y-%m-%dT%H:%M:%S' - }, - }, - 'handlers': { - 'console': { - 'class': 'logging.StreamHandler', - 'formatter': 'brief', - 'level': 'INFO', - 'stream': 'ext://sys.stderr', - }, + if logfile is not None: + logfile = pathlib.Path(logfile) + if not logfile.parent.is_dir(): + logfile.parent.mkdir(parents=True, exist_ok=True) - 'file': { + # add log file to logging configuration + LOGGING_CONFIG['handlers']['file'] = { 'class': 'logging.FileHandler', 'formatter': 'standard', 'level': 'INFO', 'filename': logfile, 'mode': 'a' } - }, - 'loggers': { - '': { - 'handlers': ['console', 'file'], - 'level': 'INFO', - }, - } - } + LOGGING_CONFIG['loggers']['']['handlers'].append('file') return LOGGING_CONFIG