import subprocess import click from pathlib import PurePath import configparser import logging from logging.handlers import RotatingFileHandler import sys APP_NAME = 'iottb' CONSOLE_LOG_FORMATS = { 0: '%(levelname)s - %(message)s', 1: '%(levelname)s - %(module)s - %(message)s', 2: '%(levelname)s - %(asctime)s - %(module)s - %(funcName)s - %(lineno)d - %(message)s' } LOGFILE_LOG_FORMAT = { 0: '%(levelname)s - %(asctime)s - %(module)s - %(message)s', 1: '%(levelname)s - %(asctime)s - %(module)s - %(funcName)s - %(message)s', 2: '%(levelname)s - %(asctime)s - %(module)s - %(funcName)s - %(lineno)d - %(message)s' } MAX_VERBOSITY = len(CONSOLE_LOG_FORMATS) - 1 assert len(LOGFILE_LOG_FORMAT) == len(CONSOLE_LOG_FORMATS), 'Log formats must be same size' def setup_logging(verbosity, debug): """ Setup root logger for iottb """ log_level = logging.ERROR logger = logging.getLogger() date_format = '%Y-%m-%d %H:%M:%S' if verbosity > 0: log_level = logging.WARNING if verbosity > MAX_VERBOSITY: verbosity = MAX_VERBOSITY log_level = logging.INFO assert verbosity <= MAX_VERBOSITY, f'Verbosity must be <= {MAX_VERBOSITY}' console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(logging.Formatter(CONSOLE_LOG_FORMATS[verbosity], datefmt=date_format)) console_handler.setLevel(logging.DEBUG) # can keep at debug since it depends on global level? logger.addHandler(console_handler) if debug: log_level = logging.DEBUG # Logfile logs INFO+, no debugs though file_handler = RotatingFileHandler(f'{APP_NAME}.log', maxBytes=10240, backupCount=5) file_handler.setFormatter(logging.Formatter(LOGFILE_LOG_FORMAT[verbosity], datefmt=date_format)) file_handler.setLevel(logging.INFO) # finnish root logger setup logger.addHandler(file_handler) logger.setLevel(log_level) return logger class Environment: def __init__(self, cfg=None, db=None, device=None): self.cfg = cfg self.db = db self.device = device pass def load_config(cfg_file_path): cfg_file = PurePath(click.get_app_dir(APP_NAME)).joinpath('iottb.cfg') @click.group() @click.option('-v', '--verbosity', type=click.IntRange(0, MAX_VERBOSITY), default=0, help='Verbosity level') @click.option('-d', '--debug', is_flag=True, default=False, help='Debug mode') @click.option('--cfg-file', type=click.Path(), default=PurePath(click.get_app_dir(APP_NAME)).joinpath('iottb.cfg'), envvar='IOTTB_CONF_HOME',) def main(debug, verbose): setup_logging(verbose, debug) if __name__ == '__main__': main(auto_envvar_prefix='IOTTB')