From 947a56b21e189d1b2f671d025305af0bfdb468bf Mon Sep 17 00:00:00 2001 From: Einar Forselv Date: Wed, 4 Dec 2019 00:31:13 +0100 Subject: [PATCH] Configurable log level: ENV + cmd --- docker-compose.yaml | 2 ++ restic_compose_backup/cli.py | 7 +++++++ restic_compose_backup/log.py | 28 ++++++++++++++++++++++------ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index a818764..9d9fee6 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -4,6 +4,8 @@ services: build: . env_file: - restic_compose_backup.env + # environment: + # - LOG_LEVEL=error volumes: # Map in docker socket - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/restic_compose_backup/cli.py b/restic_compose_backup/cli.py index 64573b4..d180f8e 100644 --- a/restic_compose_backup/cli.py +++ b/restic_compose_backup/cli.py @@ -16,6 +16,7 @@ logger = logging.getLogger(__name__) def main(): """CLI entrypoint""" args = parse_args() + log.setup(level=args.log_level) config = Config() containers = RunningContainers() @@ -132,6 +133,12 @@ def parse_args(): 'action', choices=['status', 'backup', 'start-backup-process'], ) + parser.add_argument( + '--log-level', + default=None, + choices=list(log.LOG_LEVELS.keys()), + help="Log level" + ) return parser.parse_args() diff --git a/restic_compose_backup/log.py b/restic_compose_backup/log.py index 4dbc59b..ab3c017 100644 --- a/restic_compose_backup/log.py +++ b/restic_compose_backup/log.py @@ -5,9 +5,25 @@ import sys logger = logging.getLogger('restic_compose_backup') HOSTNAME = os.environ['HOSTNAME'] -level = logging.INFO -logger.setLevel(level) -ch = logging.StreamHandler(stream=sys.stdout) -ch.setLevel(level) -ch.setFormatter(logging.Formatter(f'%(asctime)s - {HOSTNAME} - %(name)s - %(levelname)s - %(message)s')) -logger.addHandler(ch) +DEFAULT_LOG_LEVEL = logging.INFO +LOG_LEVELS = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, +} + +def setup(level: str = 'warning'): + """Set up logging""" + # Get log level from env if not set directly + if level is None: + level = os.environ.get('LOG_LEVEL') + + level = level or "" + level = LOG_LEVELS.get(level.lower(), DEFAULT_LOG_LEVEL) + logger.setLevel(level) + + ch = logging.StreamHandler(stream=sys.stdout) + ch.setLevel(level) + ch.setFormatter(logging.Formatter(f'%(asctime)s - {HOSTNAME} - %(name)s - %(levelname)s - %(message)s')) + logger.addHandler(ch)