Configurable log level: ENV + cmd

This commit is contained in:
Einar Forselv 2019-12-04 00:31:13 +01:00
parent 4ad575cfe3
commit 947a56b21e
3 changed files with 31 additions and 6 deletions

View File

@ -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

View File

@ -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()

View File

@ -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)