1"""Auxiliary functions used for logging module. 2""" 3 4# Copyright The Mbed TLS Contributors 5# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 6# 7 8import logging 9import sys 10 11def configure_logger( 12 logger: logging.Logger, 13 log_format="[%(levelname)s]: %(message)s", 14 split_level=logging.WARNING 15 ) -> None: 16 """ 17 Configure the logging.Logger instance so that: 18 - Format is set to any log_format. 19 Default: "[%(levelname)s]: %(message)s" 20 - loglevel >= split_level are printed to stderr. 21 - loglevel < split_level are printed to stdout. 22 Default: logging.WARNING 23 """ 24 class MaxLevelFilter(logging.Filter): 25 # pylint: disable=too-few-public-methods 26 def __init__(self, max_level, name=''): 27 super().__init__(name) 28 self.max_level = max_level 29 30 def filter(self, record: logging.LogRecord) -> bool: 31 return record.levelno <= self.max_level 32 33 log_formatter = logging.Formatter(log_format) 34 35 # set loglevel >= split_level to be printed to stderr 36 stderr_hdlr = logging.StreamHandler(sys.stderr) 37 stderr_hdlr.setLevel(split_level) 38 stderr_hdlr.setFormatter(log_formatter) 39 40 # set loglevel < split_level to be printed to stdout 41 stdout_hdlr = logging.StreamHandler(sys.stdout) 42 stdout_hdlr.addFilter(MaxLevelFilter(split_level - 1)) 43 stdout_hdlr.setFormatter(log_formatter) 44 45 logger.addHandler(stderr_hdlr) 46 logger.addHandler(stdout_hdlr) 47