Coverage for labnirs2snirf / log.py: 100%
23 statements
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-28 06:02 +0000
« prev ^ index » next coverage.py v7.12.0, created at 2025-11-28 06:02 +0000
1"""
2Logging configuration utilities for the labnirs2snirf package.
3"""
5from logging import (
6 CRITICAL,
7 DEBUG,
8 INFO,
9 WARNING,
10 FileHandler,
11 Formatter,
12 StreamHandler,
13 getLogger,
14)
16LOGFILE_NAME = "labnirs2snirf.log"
19def config_logger(file_logging: bool = False, verbosity_level: int = 0) -> None:
20 """
21 Configure the root logger for the application.
23 Parameters
24 ----------
25 file_logging : bool, default = False
26 If True, log messages will be written to a file. If False, log messages will
27 be printed to the console.
28 verbosity_level : int, default = 0
29 The verbosity level of the log messages. Must be between 0 and 3.
30 Possible values:
31 - 0: disabled (no logging)
32 - 1: WARNING (warnings and above)
33 - 2: INFO (informational messages and above)
34 - 3: DEBUG (debugging messages and above)
36 Notes
37 -----
38 This function should be called only once, at the start of the application,
39 and only if it's run as a script, not as a library. Most modules should invoke
40 `getLogger(__name__)` to get a module-specific logger, which will inherit the
41 configuration set here.
42 """
44 # verbosity_level -> loglevel
45 match verbosity_level:
46 case 0:
47 loglevel = CRITICAL + 1
48 case 1:
49 loglevel = WARNING
50 case 2:
51 loglevel = INFO
52 case 3:
53 loglevel = DEBUG
54 case _:
55 raise ValueError("verbosity_level must be between 0 and 3")
57 # file or stream handler with corresponding formats
58 if file_logging:
59 logfmt = Formatter(
60 # fmt="%(asctime)s %(levelname)-8s [%(module)s.%(funcName)s:%(lineno)d] %(message)s",
61 fmt="%(asctime)s %(levelname)-8s [%(name)s %(funcName)s:%(lineno)d] %(message)s",
62 # datefmt="%Y.%m.%d %H:%M:%S",
63 datefmt="%H:%M:%S",
64 )
65 # types indicated to satisfy mypy
66 handler: FileHandler | StreamHandler = FileHandler(LOGFILE_NAME, mode="a")
67 else:
68 logfmt = Formatter(
69 # fmt="%(levelname)-8s [%(module)s] %(message)s",
70 fmt="%(levelname)-8s [%(name)s] %(message)s",
71 # datefmt="%Y.%m.%d %H:%M:%S",
72 datefmt="%H:%M:%S",
73 )
74 handler = StreamHandler()
76 # Don't set level on handler, as it will make it impossible for pytest to capture logs.
77 # For whatever reason...
78 # handler.setLevel(loglevel)
79 handler.setFormatter(logfmt)
81 # assign handler to root logger
82 log = getLogger()
83 log.setLevel(loglevel)
84 log.addHandler(handler)