forked from pybamm-team/PyBaMM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.py
58 lines (43 loc) · 1.61 KB
/
logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#
# Logging class for PyBaMM
# Includes additional logging levels inspired by verboselogs
# https://pypi.org/project/verboselogs/#overview-of-logging-levels
#
# Implementation from stackoverflow
# https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-pythons-logging-facility
#
import logging
def get_log_level_func(value):
def func(self, message, *args, **kws):
if self.isEnabledFor(value):
self._log(value, message, args, **kws)
return func
# Additional levels inspired by verboselogs
new_levels = {"SPAM": 5, "VERBOSE": 15, "NOTICE": 25, "SUCCESS": 35}
for level, value in new_levels.items():
logging.addLevelName(value, level)
setattr(logging.Logger, level.lower(), get_log_level_func(value))
FORMAT = (
"%(asctime)s.%(msecs)03d - [%(levelname)s] %(module)s.%(funcName)s(%(lineno)d): "
"%(message)s"
)
LOG_FORMATTER = logging.Formatter(datefmt="%Y-%m-%d %H:%M:%S", fmt=FORMAT)
def set_logging_level(level):
logger.setLevel(level)
def _get_new_logger(name, filename=None):
new_logger = logging.getLogger(name)
if filename is None:
handler = logging.StreamHandler()
else:
handler = logging.FileHandler(filename)
handler.setFormatter(LOG_FORMATTER)
new_logger.addHandler(handler)
return new_logger
# Only the function for getting a new logger with filename not None is exposed
def get_new_logger(name, filename):
if filename is None:
raise ValueError("filename must be specified")
return _get_new_logger(name, filename)
# Create a custom logger
logger = _get_new_logger(__name__)
set_logging_level("WARNING")