Yanray Wang | 21127f7 | 2023-07-19 12:09:45 +0800 | [diff] [blame] | 1 | """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 | |
| 19 | import logging |
| 20 | import sys |
| 21 | |
| 22 | def configure_logger( |
| 23 | logger: logging.Logger, |
Yanray Wang | 15b1358 | 2023-07-26 14:48:08 +0800 | [diff] [blame] | 24 | log_format="[%(levelname)s]: %(message)s" |
Yanray Wang | 21127f7 | 2023-07-19 12:09:45 +0800 | [diff] [blame] | 25 | ) -> None: |
| 26 | """ |
| 27 | Configure the logging.Logger instance so that: |
Yanray Wang | 15b1358 | 2023-07-26 14:48:08 +0800 | [diff] [blame] | 28 | - Format is set to any log_format. |
Yanray Wang | 21127f7 | 2023-07-19 12:09:45 +0800 | [diff] [blame] | 29 | 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 Wang | 15b1358 | 2023-07-26 14:48:08 +0800 | [diff] [blame] | 42 | log_formatter = logging.Formatter(log_format) |
Yanray Wang | 21127f7 | 2023-07-19 12:09:45 +0800 | [diff] [blame] | 43 | |
| 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) |