My main program logs to its own log file and the sub-process should have its own log file. I replaced the logger object inside the multiprocessing process, but the logging data from the sub-process is additionally redirected to the main log file.
How can I prevent this?
The structure looks like this:
JavaScript
x
70
70
1
import logging
2
import sys
3
import os
4
from pathlib import Path
5
import multiprocessing
6
import time
7
8
import requests
9
10
11
class ProcessFilter(logging.Filter):
12
"""Only accept log records from a specific pid."""
13
14
def __init__(self, pid):
15
self._pid = pid
16
17
def filter(self, record):
18
return record.process == self._pid
19
20
21
def create_logger(file):
22
log = logging.getLogger(__name__)
23
log.setLevel(logging.DEBUG)
24
log.addFilter(ProcessFilter(pid=os.getpid()))
25
file_handler = logging.FileHandler(file)
26
stream_handler = logging.StreamHandler(sys.stdout)
27
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s',
28
datefmt='%a, %d %b %Y %H:%M:%S')
29
file_handler.setFormatter(formatter)
30
stream_handler.setFormatter(formatter)
31
log.addHandler(file_handler)
32
log.addHandler(stream_handler)
33
return log
34
35
36
def subprocess_init():
37
global log
38
sub_log_file = str(Path.home()) + '/logfile_sub.log'
39
log = create_logger(sub_log_file)
40
do_subprocess_stuff()
41
42
43
def do_subprocess_stuff():
44
count = 0
45
while True:
46
create_log("subprocess", count)
47
time.sleep(5)
48
count += 1
49
50
51
def main_tasks():
52
num = 10
53
while num > 0:
54
create_log("main", num)
55
time.sleep(5)
56
num -= 1
57
58
59
def create_log(text, num):
60
log.debug(text + " log %s", num)
61
62
63
if __name__ == '__main__':
64
file = str(Path.home()) + '/logfile.log'
65
log = create_logger(file)
66
sub_process = multiprocessing.Process(target=subprocess_init, args=())
67
sub_process.daemon = True
68
sub_process.start()
69
main_tasks()
70
Advertisement
Answer
I am simply translating this answer to fit multiprocessing.
JavaScript
1
11
11
1
import logging
2
3
class ProcessFilter(logging.Filter):
4
"""Only accept log records from a specific pid."""
5
6
def __init__(self, pid):
7
self._pid = pid
8
9
def filter(self, record):
10
return record.process == self._pid
11
JavaScript
1
17
17
1
import logging
2
import os
3
4
def create_logger(file):
5
log = logging.getLogger('') # why use this logger and not __name__ ?
6
log.setLevel(logging.DEBUG)
7
log.addFilter(ProcessFilter(pid=os.getpid())) # logger wide filter
8
file_handler = logging.FileHandler(file)
9
stream_handler = logging.StreamHandler(sys.stdout)
10
formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s',
11
datefmt='%a, %d %b %Y %H:%M:%S')
12
file_handler.setFormatter(formatter)
13
stream_handler.setFormatter(formatter)
14
log.addHandler(file_handler)
15
log.addHandler(stream_handler)
16
return log
17
NB. you can also put the filter on a specific handler