Coverage for src / lstautorta / utils / logging.py: 28%

21 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-08-10 11:56 +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}) 

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 

31 sys.excepthook = handle_exception 

32 

33 

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

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

36 

37 Parameters 

38 ---------- 

39 log_level : str, Optional 

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

41 log_filename : str, Optional 

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

43 format_title : str, Optional 

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

45 """ 

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

47 log_uncaught_exceptions() # log all uncaught exceptions as well 

48 

49 logging_format = f"%(asctime)s - %(levelname)s - {format_title} - %(filename)s:%(lineno)s - %(message)s" 

50 logging_level = LOGGING_LEVELS(log_level) 

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

52 if log_filename: # and also output to file if asked 

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

54 logging.basicConfig( 

55 level=logging_level.name, 

56 format=logging_format, 

57 handlers=handlers, 

58 force=True, 

59 ) 

60 

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