2023-07-19 06:09:45 +02:00
|
|
|
"""Auxiliary functions used for logging module.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Copyright The Mbed TLS Contributors
|
2023-11-02 20:47:20 +01:00
|
|
|
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
|
2023-07-19 06:09:45 +02:00
|
|
|
#
|
|
|
|
|
|
|
|
import logging
|
|
|
|
import sys
|
|
|
|
|
|
|
|
def configure_logger(
|
|
|
|
logger: logging.Logger,
|
2023-08-14 04:33:37 +02:00
|
|
|
log_format="[%(levelname)s]: %(message)s",
|
|
|
|
split_level=logging.WARNING
|
2023-07-19 06:09:45 +02:00
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Configure the logging.Logger instance so that:
|
2023-07-26 08:48:08 +02:00
|
|
|
- Format is set to any log_format.
|
2023-07-19 06:09:45 +02:00
|
|
|
Default: "[%(levelname)s]: %(message)s"
|
2023-08-14 04:33:37 +02:00
|
|
|
- loglevel >= split_level are printed to stderr.
|
|
|
|
- loglevel < split_level are printed to stdout.
|
|
|
|
Default: logging.WARNING
|
2023-07-19 06:09:45 +02:00
|
|
|
"""
|
|
|
|
class MaxLevelFilter(logging.Filter):
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
def __init__(self, max_level, name=''):
|
|
|
|
super().__init__(name)
|
|
|
|
self.max_level = max_level
|
|
|
|
|
|
|
|
def filter(self, record: logging.LogRecord) -> bool:
|
|
|
|
return record.levelno <= self.max_level
|
|
|
|
|
2023-07-26 08:48:08 +02:00
|
|
|
log_formatter = logging.Formatter(log_format)
|
2023-07-19 06:09:45 +02:00
|
|
|
|
2023-08-14 04:33:37 +02:00
|
|
|
# set loglevel >= split_level to be printed to stderr
|
2023-07-19 06:09:45 +02:00
|
|
|
stderr_hdlr = logging.StreamHandler(sys.stderr)
|
2023-08-14 04:33:37 +02:00
|
|
|
stderr_hdlr.setLevel(split_level)
|
2023-07-19 06:09:45 +02:00
|
|
|
stderr_hdlr.setFormatter(log_formatter)
|
|
|
|
|
2023-08-14 04:33:37 +02:00
|
|
|
# set loglevel < split_level to be printed to stdout
|
2023-07-19 06:09:45 +02:00
|
|
|
stdout_hdlr = logging.StreamHandler(sys.stdout)
|
2023-08-14 04:33:37 +02:00
|
|
|
stdout_hdlr.addFilter(MaxLevelFilter(split_level - 1))
|
2023-07-19 06:09:45 +02:00
|
|
|
stdout_hdlr.setFormatter(log_formatter)
|
|
|
|
|
|
|
|
logger.addHandler(stderr_hdlr)
|
|
|
|
logger.addHandler(stdout_hdlr)
|