Wei-Yu Chen | ad55cb8 | 2022-02-15 20:07:01 +0800 | [diff] [blame^] | 1 | # SPDX-FileCopyrightText: 2020 The Magma Authors. |
| 2 | # SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org> |
| 3 | # |
| 4 | # SPDX-License-Identifier: BSD-3-Clause |
Wei-Yu Chen | 49950b9 | 2021-11-08 19:19:18 +0800 | [diff] [blame] | 5 | |
| 6 | import logging |
| 7 | from logging.handlers import RotatingFileHandler |
| 8 | |
| 9 | LOG_FILE = './enodebd.log' |
| 10 | MAX_BYTES = 1024 * 1024 * 10 # 10MB |
| 11 | BACKUP_COUNT = 5 # 10MB, 5 files, 50MB total |
| 12 | |
| 13 | |
| 14 | class EnodebdLogger: |
| 15 | """ |
| 16 | EnodebdLogger backs up debug logs with a RotatingFileHandler. |
| 17 | |
| 18 | Debug logs will be propagated to root level if the root logger is set to |
| 19 | debug level. |
| 20 | """ |
| 21 | |
| 22 | _LOGGER = logging.getLogger(__name__) # type: logging.Logger |
| 23 | |
| 24 | @staticmethod |
| 25 | def init() -> None: |
| 26 | if logging.root.level is not logging.DEBUG: |
| 27 | EnodebdLogger._LOGGER.propagate = False |
| 28 | handler = RotatingFileHandler( |
| 29 | LOG_FILE, |
| 30 | maxBytes=MAX_BYTES, |
| 31 | backupCount=BACKUP_COUNT, |
| 32 | ) |
| 33 | formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s') |
| 34 | handler.setFormatter(formatter) |
| 35 | EnodebdLogger._LOGGER.addHandler(handler) |
| 36 | EnodebdLogger._LOGGER.setLevel(logging.DEBUG) |
| 37 | |
| 38 | @staticmethod |
| 39 | def debug(msg, *args, **kwargs): |
| 40 | EnodebdLogger._LOGGER.debug(msg, *args, **kwargs) |
| 41 | |
| 42 | @staticmethod |
| 43 | def info(msg, *args, **kwargs): |
| 44 | if not EnodebdLogger._LOGGER.propagate: |
| 45 | logging.info(msg, *args, **kwargs) |
| 46 | EnodebdLogger._LOGGER.info(msg, *args, **kwargs) |
| 47 | |
| 48 | @staticmethod |
| 49 | def warning(msg, *args, **kwargs): |
| 50 | if not EnodebdLogger._LOGGER.propagate: |
| 51 | logging.warning(msg, *args, **kwargs) |
| 52 | EnodebdLogger._LOGGER.warning(msg, *args, **kwargs) |
| 53 | |
| 54 | @staticmethod |
| 55 | def error(msg, *args, **kwargs): |
| 56 | if not EnodebdLogger._LOGGER.propagate: |
| 57 | logging.error(msg, *args, **kwargs) |
| 58 | EnodebdLogger._LOGGER.error(msg, *args, **kwargs) |
| 59 | |
| 60 | @staticmethod |
| 61 | def exception(msg, *args, **kwargs): |
| 62 | if not EnodebdLogger._LOGGER.propagate: |
| 63 | logging.exception(msg, *args, **kwargs) |
| 64 | EnodebdLogger._LOGGER.exception(msg, *args, **kwargs) |
| 65 | |
| 66 | @staticmethod |
| 67 | def critical(msg, *args, **kwargs): |
| 68 | if not EnodebdLogger._LOGGER.propagate: |
| 69 | logging.critical(msg, *args, **kwargs) |
| 70 | EnodebdLogger._LOGGER.critical(msg, *args, **kwargs) |