config: use a section to configure console logging

This commit is contained in:
Benjamin Renard 2022-02-24 14:58:13 +01:00
parent ef94c6969f
commit 63600416b3

View file

@ -25,6 +25,7 @@ log = logging.getLogger(__name__)
# Constants # Constants
DEFAULT_ENCODING = 'utf-8' DEFAULT_ENCODING = 'utf-8'
DEFAULT_CONFIG_DIRPATH = os.path.expanduser('./') DEFAULT_CONFIG_DIRPATH = os.path.expanduser('./')
DEFAULT_CONSOLE_LOG_FORMAT = '%(asctime)s - %(module)s:%(lineno)d - %(levelname)s - %(message)s'
class BaseOption: # pylint: disable=too-many-instance-attributes class BaseOption: # pylint: disable=too-many-instance-attributes
@ -133,7 +134,8 @@ class BaseOption: # pylint: disable=too-many-instance-attributes
def parser_help(self): def parser_help(self):
""" Get option help message in arguments parser options """ """ Get option help message in arguments parser options """
if self.arg_help and self.default is not None: if self.arg_help and self.default is not None:
return '{0} (Default: {1})'.format(self.arg_help, self.default) return '{0} (Default: {1})'.format(
self.arg_help, re.sub(r'%([^%])', r'%%\1', str(self.default)))
if self.arg_help: if self.arg_help:
return self.arg_help return self.arg_help
return None return None
@ -749,12 +751,14 @@ class Config: # pylint: disable=too-many-instance-attributes
help='Show verbose messages' help='Show verbose messages'
) )
self.options_parser.add_argument( section = self.add_section('console', comment='Console logging')
'-C', section.add_option(
'--console', BooleanOption, 'enabled', default=False,
action='store_true', arg='--console', short_arg='-C',
help='Log on console' comment='Enable/disable console log')
) section.add_option(
StringOption, 'log_format', default=DEFAULT_CONSOLE_LOG_FORMAT,
arg='--console-log-format', comment='Console log format')
self.add_options_to_parser(self.options_parser) self.add_options_to_parser(self.options_parser)
@ -813,10 +817,11 @@ class Config: # pylint: disable=too-many-instance-attributes
elif options.verbose: elif options.verbose:
logging.getLogger().setLevel(logging.INFO) logging.getLogger().setLevel(logging.INFO)
if options.console: if self.get('console', 'enabled'):
console_handler = logging.StreamHandler(sys.stdout) console_handler = logging.StreamHandler(sys.stdout)
console_formater = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') if self.get('console', 'log_format'):
console_handler.setFormatter(console_formater) console_formater = logging.Formatter(self.get('console', 'log_format'))
console_handler.setFormatter(console_formater)
logging.getLogger().addHandler(console_handler) logging.getLogger().addHandler(console_handler)
if execute_callback: if execute_callback: