blob: db1ebfe5cf48c34bf36f251a73726a9df5d20a3b [file] [log] [blame]
Yanray Wang21127f72023-07-19 12:09:45 +08001"""Auxiliary functions used for logging module.
2"""
3
4# Copyright The Mbed TLS Contributors
5# SPDX-License-Identifier: Apache-2.0
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18
19import logging
20import sys
21
22def configure_logger(
23 logger: logging.Logger,
Yanray Wang1998aac2023-08-14 10:33:37 +080024 log_format="[%(levelname)s]: %(message)s",
25 split_level=logging.WARNING
Yanray Wang21127f72023-07-19 12:09:45 +080026 ) -> None:
27 """
28 Configure the logging.Logger instance so that:
Yanray Wang15b13582023-07-26 14:48:08 +080029 - Format is set to any log_format.
Yanray Wang21127f72023-07-19 12:09:45 +080030 Default: "[%(levelname)s]: %(message)s"
Yanray Wang1998aac2023-08-14 10:33:37 +080031 - loglevel >= split_level are printed to stderr.
32 - loglevel < split_level are printed to stdout.
33 Default: logging.WARNING
Yanray Wang21127f72023-07-19 12:09:45 +080034 """
35 class MaxLevelFilter(logging.Filter):
36 # pylint: disable=too-few-public-methods
37 def __init__(self, max_level, name=''):
38 super().__init__(name)
39 self.max_level = max_level
40
41 def filter(self, record: logging.LogRecord) -> bool:
42 return record.levelno <= self.max_level
43
Yanray Wang15b13582023-07-26 14:48:08 +080044 log_formatter = logging.Formatter(log_format)
Yanray Wang21127f72023-07-19 12:09:45 +080045
Yanray Wang1998aac2023-08-14 10:33:37 +080046 # set loglevel >= split_level to be printed to stderr
Yanray Wang21127f72023-07-19 12:09:45 +080047 stderr_hdlr = logging.StreamHandler(sys.stderr)
Yanray Wang1998aac2023-08-14 10:33:37 +080048 stderr_hdlr.setLevel(split_level)
Yanray Wang21127f72023-07-19 12:09:45 +080049 stderr_hdlr.setFormatter(log_formatter)
50
Yanray Wang1998aac2023-08-14 10:33:37 +080051 # set loglevel < split_level to be printed to stdout
Yanray Wang21127f72023-07-19 12:09:45 +080052 stdout_hdlr = logging.StreamHandler(sys.stdout)
Yanray Wang1998aac2023-08-14 10:33:37 +080053 stdout_hdlr.addFilter(MaxLevelFilter(split_level - 1))
Yanray Wang21127f72023-07-19 12:09:45 +080054 stdout_hdlr.setFormatter(log_formatter)
55
56 logger.addHandler(stderr_hdlr)
57 logger.addHandler(stdout_hdlr)