Coverage for lst_auto_rta/utils/logging.py: 73%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.9, created at 2024-12-22 14:47 +0000

1import logging 

2import sys 

3from enum import Enum 

4 

5# Mapping between logging levels exposed to users, and logging levels in software 

6# Users level should eventually follow ACADA AE Logging ICD https://redmine.cta-observatory.org/dmsf/files/14915/view 

7LOGGING_LEVELS_DICT = { 

8 "DEBUG": logging.DEBUG, 

9 "INFO": logging.INFO, 

10 "WARNING": logging.WARNING, 

11 "ERROR": logging.ERROR, 

12 "CRITICAL": logging.CRITICAL, 

13} 

14 

15# Enum class of logging levels, to constraint the variable type in configuration json schema. 

16LOGGING_LEVELS = Enum("LOGGING_LEVELS", {v: v for v in LOGGING_LEVELS_DICT.keys()}) 

17 

18 

19def log_uncaught_exceptions(): 

20 """Makes all uncaught exception to be logged by the default logger. 

21 

22 Keyboard exceptions and children classes are not logged so one can kill the program with ctr+C. 

23 """ 

24 

25 def handle_exception(exc_type, exc_value, exc_traceback): 

26 if not issubclass(exc_type, KeyboardInterrupt): 

27 logging.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) 

28 

29 sys.__excepthook__(exc_type, exc_value, exc_traceback) 

30 return 

31 

32 sys.excepthook = handle_exception 

33 

34 

35def init_logging(log_level: str = "DEBUG", log_filename: str = "", format_title: str = "LST AUTO RTA"): 

36 """(Re-)initialize all loggers (Stream and file logger) 

37 

38 Parameters 

39 ---------- 

40 log_level : str, Optional 

41 Log level of python logging's module to apply to all loggers. Default: DEBUG 

42 log_filename : str, Optional 

43 Path to the log file for the file logger. Default "" 

44 format_title : str, Optional 

45 Log line format "title" field. Default "LST AUTO RTA" 

46 """ 

47 

48 logging.captureWarnings(True) # log all warnings from the warnings module. 

49 log_uncaught_exceptions() # log all uncaught exceptions as well 

50 

51 logging_format = "%(asctime)s - %(levelname)s - {} - %(filename)s:%(lineno)s - %(message)s".format(format_title) 

52 logging_level = LOGGING_LEVELS(log_level) 

53 handlers = [logging.StreamHandler()] # output to stderr 

54 if log_filename: # and also output to file if asked 54 ↛ 56line 54 didn't jump to line 56 because the condition on line 54 was always true

55 handlers.append(logging.FileHandler(log_filename)) 

56 logging.basicConfig( 

57 level=logging_level.name, 

58 format=logging_format, 

59 handlers=handlers, 

60 force=True, 

61 ) 

62 

63 logging.info("Logging configured - start logging")