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
« prev ^ index » next coverage.py v7.13.5, created at 2026-08-10 11:56 +0000
1import logging
2import sys
3from enum import Enum
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}
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})
19def log_uncaught_exceptions():
20 """Makes all uncaught exception to be logged by the default logger.
22 Keyboard exceptions and children classes are not logged so one can kill the program with ctr+C.
23 """
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))
29 sys.__excepthook__(exc_type, exc_value, exc_traceback)
31 sys.excepthook = handle_exception
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)
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
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 )
61 logging.info("Logging configured - start logging")