Coverage for src/phoenixpackagecleanup/logging_utils.py: 21%

20 statements  

« prev     ^ index     » next       coverage.py v7.10.3, created at 2025-09-05 18:23 +0000

1import logging 

2import sys 

3from pathlib import Path 

4 

5 

6def log_uncaught_exceptions(): 

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

8 

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

10 """ 

11 

12 def handle_exception(exc_type, exc_value, exc_traceback): 

13 if not issubclass(exc_type, KeyboardInterrupt): 

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

15 

16 sys.__excepthook__(exc_type, exc_value, exc_traceback) 

17 return 

18 

19 sys.excepthook = handle_exception 

20 

21 

22def init_logging(log_header_str: str, log_filename: Path | None, log_level: str): 

23 """(Re-)initialize all loggers""" 

24 

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

26 log_uncaught_exceptions() # log all uncaught exceptions as well 

27 

28 logging_format = "%(asctime)s %(levelname)s {} %(pathname)s:%(lineno)s:%(funcName)s %(message)s".format( 

29 log_header_str 

30 ) 

31 handlers = [] 

32 if log_filename is not None: # write log to file 

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

34 else: # write log to standard output and error 

35 handlers.append(logging.StreamHandler()) 

36 logging.basicConfig( 

37 level=log_level, 

38 format=logging_format, 

39 handlers=handlers, 

40 force=True, 

41 ) 

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