-
Notifications
You must be signed in to change notification settings - Fork 45
/
logger.py
57 lines (48 loc) · 1.8 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
import os
import logging as py_logging
_log_level = {
None: py_logging.NOTSET,
"debug": py_logging.DEBUG,
"info": py_logging.INFO,
"warning": py_logging.WARNING,
"error": py_logging.ERROR,
"critical": py_logging.CRITICAL
}
def get_logger(
log_file_path=None,
name="default_log",
level=None
):
directory = os.path.dirname(log_file_path)
if os.path.isdir(directory) and not os.path.exists(directory):
os.makedirs(directory)
root_logger = py_logging.getLogger(name)
handlers = root_logger.handlers
def _check_file_handler(logger, filepath):
for handler in logger.handlers:
if isinstance(handler, py_logging.FileHandler):
handler.baseFilename
return handler.baseFilename == os.path.abspath(filepath)
return False
if (log_file_path is not None and not
_check_file_handler(root_logger, log_file_path)):
log_formatter = py_logging.Formatter(
"%(asctime)s [%(levelname)-5.5s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler = py_logging.FileHandler(log_file_path)
file_handler.setFormatter(log_formatter)
root_logger.addHandler(file_handler)
if any([type(h) == py_logging.StreamHandler for h in handlers]):
return root_logger
level_format = "\x1b[36m[%(levelname)-5.5s]\x1b[0m"
log_formatter = py_logging.Formatter(f"{level_format} %(message)s")
console_handler = py_logging.StreamHandler()
console_handler.setFormatter(log_formatter)
root_logger.addHandler(console_handler)
root_logger.setLevel(_log_level[level])
return root_logger
if __name__ == "__main__":
logger = get_logger("test.log", name="test", level="info")
logger.info("Test")
logger.info("Test2")
logger.info("Test3")