blob: 85a3f19ace7b553b831e09afc7dd2b881e345b7d [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 Wang15b13582023-07-26 14:48:08 +080024 log_format="[%(levelname)s]: %(message)s"
Yanray Wang21127f72023-07-19 12:09:45 +080025 ) -> None:
26 """
27 Configure the logging.Logger instance so that:
Yanray Wang15b13582023-07-26 14:48:08 +080028 - Format is set to any log_format.
Yanray Wang21127f72023-07-19 12:09:45 +080029 Default: "[%(levelname)s]: %(message)s"
30 - loglevel >= WARNING are printed to stderr.
31 - loglevel < WARNING are printed to stdout.
32 """
33 class MaxLevelFilter(logging.Filter):
34 # pylint: disable=too-few-public-methods
35 def __init__(self, max_level, name=''):
36 super().__init__(name)
37 self.max_level = max_level
38
39 def filter(self, record: logging.LogRecord) -> bool:
40 return record.levelno <= self.max_level
41
Yanray Wang15b13582023-07-26 14:48:08 +080042 log_formatter = logging.Formatter(log_format)
Yanray Wang21127f72023-07-19 12:09:45 +080043
44 # set loglevel >= WARNING to be printed to stderr
45 stderr_hdlr = logging.StreamHandler(sys.stderr)
46 stderr_hdlr.setLevel(logging.WARNING)
47 stderr_hdlr.setFormatter(log_formatter)
48
49 # set loglevel <= INFO to be printed to stdout
50 stdout_hdlr = logging.StreamHandler(sys.stdout)
51 stdout_hdlr.addFilter(MaxLevelFilter(logging.INFO))
52 stdout_hdlr.setFormatter(log_formatter)
53
54 logger.addHandler(stderr_hdlr)
55 logger.addHandler(stdout_hdlr)