-
Notifications
You must be signed in to change notification settings - Fork 3
/
log.py
49 lines (40 loc) · 1.5 KB
/
log.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
import os, logging, __main__, sys
import logging.handlers
from .config import config, ConfigError
try:
name = os.path.basename(__main__.__file__).split('.')[0] # log identifier/file will be the same as the file being run
if name == "__main__":
name = os.path.dirname(__main__.__file__).split('/')[-1]
except AttributeError:
name = "python"
log = logging.getLogger(name)
log.setLevel(logging.DEBUG)
log.propagate = False
try:
log_to_file = config['log']
except ConfigError:
log_to_file = False
if log_to_file:
logdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "logs"))
if not os.path.isdir(logdir):
os.makedirs(logdir)
logfile = os.path.join(logdir, "%s.log" % name)
logfile = logging.handlers.TimedRotatingFileHandler(logfile, 'midnight')
logfile.setLevel(logging.DEBUG)
log.addHandler(logfile)
try:
log_to_terminal = config['tail']
except ConfigError:
log_to_terminal = True
if log_to_terminal:
terminal = logging.StreamHandler(sys.stdout)
terminal.setLevel(logging.DEBUG)
log.addHandler(terminal)
formatter = logging.Formatter("%(asctime)s |%(levelname)s| %(message)s <%(filename)s:%(lineno)d>")
if log_to_file:
logfile.setFormatter(formatter)
if log_to_terminal:
terminal.setFormatter(formatter)
def exc(e):
return "%s <%s:%s> %s" % (sys.exc_info()[0].__name__, os.path.split(sys.exc_info()[2].tb_frame.f_code.co_filename)[1], sys.exc_info()[2].tb_lineno, e)
log.exc = exc