-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathlogger.py
46 lines (37 loc) · 1.33 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
import logging
from logging.handlers import RotatingFileHandler
import os
def get_logger(name, log_path=os.path.join(os.path.dirname(__file__), "main.log"), console=False):
"""
Simple logging wrapper that returns logger
configured to log into file and console.
Args:
name (str): name of logger
log_path (str): path of log file
console (bool): whether to log on console
Returns:
logging.Logger: configured logger
"""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# ensure that logging handlers are not duplicated
for handler in list(logger.handlers):
logger.removeHandler(handler)
# rotating file handler
if log_path:
fh = RotatingFileHandler(log_path,
maxBytes=2 ** 20, # 1 MB
backupCount=1) # 1 backup
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
# console handler
if console:
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(ch)
if len(logger.handlers) == 0:
logger.addHandler(logging.NullHandler())
return logger