-
Notifications
You must be signed in to change notification settings - Fork 3
/
log.py
93 lines (71 loc) · 2.68 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""
Logging class for jd2chm
"""
import logging
import console
# CRITICAL = 5, ERROR = 4, WARNING = 3, INFO = 2, DEBUG = 1, NOTSET = 0.
DEFAULT_LOG_LEVEL = 2
class WinHandler(logging.Handler):
"""EditCtrl Handler (for jd2chm UI, if available)"""
def __init__(self, win):
logging.Handler.__init__(self)
self.win = win
def emit(self, record):
if self.win:
line = self.format(record)
self.win.addLogText(line)
class ColorHandler(logging.StreamHandler):
"""Color handler for the console"""
def __init__(self):
logging.StreamHandler.__init__(self)
def emit(self, record):
if record.levelno == logging.DEBUG:
console.set_color(console.FOREGROUND_MAGENTA)
if record.levelno == logging.WARNING:
console.set_color(console.FOREGROUND_YELLOW)
if record.levelno == logging.ERROR:
console.set_color(console.FOREGROUND_RED)
if record.levelno == logging.CRITICAL:
console.set_bright_color(console.FOREGROUND_RED)
line = self.format(record)
print(line)
console.set_color()
class Jd2chmLogging:
DEBUG = 1
INFO = 2
def __init__(self, level=INFO):
self.logger = logging.getLogger('jd2chm')
self.formatter = logging.Formatter('[%(asctime)s] %(message)s', '%Y-%m-%d %H:%M:%S')
self.set_level(level)
# self.stream_handler = logging.StreamHandler()
self.stream_handler = ColorHandler()
self.stream_handler.setFormatter(self.formatter)
self.logger.addHandler(self.stream_handler)
self.win_handler = None
def add_win_handler(self, win):
"""Add a windows handler to allow logging in the jd2chm UI (if available)."""
self.win_handler = WinHandler(win)
self.win_handler.setFormatter(self.formatter)
self.logger.addHandler(self.win_handler)
def set_log_file(self, log_file):
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(self.formatter)
self.logger.addHandler(file_handler)
def set_level(self, level=2):
"""level is between 0 and 5: CRITICAL = 5, ERROR = 4, WARNING = 3, INFO = 2, DEBUG = 1, NOTSET = 0."""
if level not in range(6):
level = self.INFO
self.logger.setLevel(level * 10)
@staticmethod
def shutdown():
logging.shutdown()
_logging = None
def get_logging(level=2):
"""Return the singleton logging."""
global _logging
if not _logging:
_logging = Jd2chmLogging(level)
return _logging
def get_logger(level=2):
"""Facilitate sharing the logger across the different modules."""
return get_logging(level=2).logger