kupferbootstrap/logger.py

50 lines
1.6 KiB
Python
Raw Permalink Normal View History

2021-08-04 18:36:37 +02:00
import click
2022-05-07 15:27:55 +02:00
import coloredlogs
2021-08-04 18:36:37 +02:00
import logging
import sys
from typing import Optional
2021-09-12 06:12:39 +02:00
def setup_logging(verbose: bool, quiet: bool = False, force_colors: Optional[bool] = None, log_setup: bool = True):
2022-05-07 15:27:55 +02:00
level_colors = coloredlogs.DEFAULT_LEVEL_STYLES | {'info': {'color': 'magenta', 'bright': True}, 'debug': {'color': 'blue', 'bright': True}}
field_colors = coloredlogs.DEFAULT_FIELD_STYLES | {'asctime': {'color': 'white', 'faint': True}}
level = logging.DEBUG if verbose and not quiet else (logging.INFO if not quiet else logging.ERROR)
2022-05-07 15:27:55 +02:00
coloredlogs.install(
2021-08-04 18:36:37 +02:00
stream=sys.stdout,
2022-05-07 15:27:55 +02:00
fmt='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
2021-08-08 18:32:42 +02:00
level=level,
2022-05-07 15:27:55 +02:00
level_styles=level_colors,
field_styles=field_colors,
isatty=force_colors,
2021-08-04 18:36:37 +02:00
)
# don't raise Exceptions when e.g. output stream is closed
logging.raiseExceptions = False
if log_setup:
logging.debug('Logger: Logging set up.')
if force_colors is not None:
logging.debug(f'Logger: Force-{"en" if force_colors else "dis"}abled colors')
2021-08-04 18:36:37 +02:00
verbose_option = click.option(
'-v',
'--verbose',
is_flag=True,
2021-08-08 18:32:42 +02:00
help='Enables verbose logging',
2021-08-04 18:36:37 +02:00
)
quiet_option = click.option(
'-q',
'--quiet',
is_flag=True,
help='Disable most logging, only log errors. (Currently only affects KBS logging, not called subprograms)',
)
color_option = click.option(
'--force-colors/--no-colors',
is_flag=True,
default=None,
help='Force enable/disable log coloring. Defaults to autodetection.',
)