-
Notifications
You must be signed in to change notification settings - Fork 1
/
perThreadLog.py
110 lines (86 loc) · 2.86 KB
/
perThreadLog.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import threading
import logging
import logging.config
class ThreadLogFilter(logging.Filter):
"""
This filter only show log entries for specified thread name
"""
def __init__(self, thread_name, *args, **kwargs):
logging.Filter.__init__(self, *args, **kwargs)
self.thread_name = thread_name
def filter(self, record):
return record.threadName == self.thread_name
def start_thread_logging(path):
"""
Add a log handler to separate file for current thread
"""
thread_name = threading.Thread.getName(threading.current_thread())
log_file = '{}.log'.format(path)
log_handler = logging.FileHandler(log_file)
log_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s"
"| %(threadName)-11s"
"| %(levelname)-5s"
"| %(message)s", '%Y-%m-%d %H:%M:%S')
log_handler.setFormatter(formatter)
log_filter = ThreadLogFilter(thread_name)
log_handler.addFilter(log_filter)
logger = logging.getLogger()
logger.addHandler(log_handler)
return log_handler
def stop_thread_logging(log_handler):
# Remove thread log handler from root logger
logging.getLogger().removeHandler(log_handler)
# Close the thread log handler so that the lock on log file can be released
log_handler.close()
def worker():
thread_log_handler = start_thread_logging()
logging.info('Info log entry in sub thread.')
logging.debug('Debug log entry in sub thread.')
stop_thread_logging(thread_log_handler)
def config_root_logger(path):
log_file = '{}.log'.format(path)
formatter = "%(asctime)-15s" \
"| %(threadName)-11s" \
"| %(levelname)-5s" \
"| %(message)s"
logging.config.dictConfig({
'version': 1,
'formatters': {
'root_formatter': {
'format': formatter
}
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'root_formatter'
},
'log_file': {
'class': 'logging.FileHandler',
'level': 'DEBUG',
'filename': log_file,
'formatter': 'root_formatter',
}
},
'loggers': {
'': {
'handlers': [
'console',
'log_file',
],
'level': 'DEBUG',
'propagate': True
}
}
})
if __name__ == '__main__':
config_root_logger(path)
logging.info('Info log entry in main thread.')
logging.debug('Debug log entry in main thread.')
for i in range(3):
t = threading.Thread(target=worker,
name='Thread-{}'.format(i),
args=[])
t.start()