Coverage for lib/utils/logging.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2025-07-28 07:25 +0000

1#!/usr/bin/python3 

2# -*- coding: utf-8 -*- 

3 

4# Hermes : Change Data Capture (CDC) tool from any source(s) to any target 

5# Copyright (C) 2023, 2024 INSA Strasbourg 

6# 

7# This file is part of Hermes. 

8# 

9# Hermes is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# Hermes is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with Hermes. If not, see <https://www.gnu.org/licenses/>. 

21 

22 

23from typing import TYPE_CHECKING 

24 

25if TYPE_CHECKING: # pragma: no cover 

26 # Only for type hints, won't import at runtime 

27 from lib.config import HermesConfig 

28 

29import sys 

30import logging 

31from logging.handlers import TimedRotatingFileHandler 

32 

33 

34def setup_logger(config: "HermesConfig"): 

35 """Setup logging for the whole app""" 

36 

37 loglevels = { 

38 "critical": logging.CRITICAL, 

39 "error": logging.ERROR, 

40 "warning": logging.WARNING, 

41 "info": logging.INFO, 

42 "debug": logging.DEBUG, 

43 } 

44 

45 __hermes__.logger.setLevel(loglevels[config["hermes"]["logs"]["verbosity"]]) 

46 

47 log_format = logging.Formatter( 

48 "%(levelname)s:%(asctime)s:%(filename)s:%(lineno)d:%(funcName)s():%(message)s" 

49 ) 

50 

51 # Disable stderr output when ran from unit tests 

52 if "unittest" in sys.modules: 

53 __hermes__.logger.addHandler(logging.NullHandler()) 

54 else: # pragma: no cover 

55 stream_handler = logging.StreamHandler() 

56 stream_handler.setFormatter(log_format) 

57 stream_handler.setLevel(loglevels[config["hermes"]["logs"]["verbosity"]]) 

58 __hermes__.logger.addHandler(stream_handler) 

59 

60 # log file output when set up 

61 if config["hermes"]["logs"]["logfile"] is not None: # pragma: no cover 

62 file_handler = TimedRotatingFileHandler( 

63 config["hermes"]["logs"]["logfile"], 

64 when="midnight", 

65 backupCount=config["hermes"]["logs"]["backup_count"], 

66 ) 

67 file_handler.setFormatter(log_format) 

68 file_handler.setLevel(loglevels[config["hermes"]["logs"]["verbosity"]]) 

69 __hermes__.logger.addHandler(file_handler)