-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmultiprocessing_logging.py
65 lines (50 loc) · 2.21 KB
/
multiprocessing_logging.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
# -*- coding: utf-8 -*-`
# Copyright (c) Centre Inria d'Université Côte d'Azur, University of Cambridge 2023.
# Authors: Kacper Pluta <[email protected]>, Alwyn Mathew <[email protected]>
# This file cannot be used without a written permission from the author(s).
# based on https://www.jamesfheath.com/2020/06/logging-in-python-while-multiprocessing.html and
# https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes
import logging
import logging.handlers
import sys
import traceback
from os import path
def listener_configurer(log_name, log_file_path,fmtr=logging.Formatter('%(asctime)s : %(message)s',
datefmt='%d-%b-%y %H:%M:%S')):
""" Configures and returns a log file based on
the given name
Arguments:
log_name (str): String of the log name to use
log_file_path (str): String of the log file path
Returns:
logger: configured logging object
"""
logger = logging.getLogger(log_name)
fh = logging.FileHandler(path.join(log_file_path, f'{log_name}.log'), encoding='utf-8')
fh.setFormatter(fmtr)
logger.setLevel(logging.INFO)
current_fh_names = [fh.__dict__.get('baseFilename', '') for fh in logger.handlers]
if not fh.__dict__['baseFilename'] in current_fh_names: # This prevents multiple logs to the same file
logger.addHandler(fh)
return logger
def listener_process(queue, configurer, log_name, log_file_path):
""" Listener process is a target for a multiprocess process
that runs and listens to a queue for logging events.
Arguments:
queue (multiprocessing.manager.Queue): queue to monitor
configurer (func): configures loggers
log_name (str): name of the log to use
Returns:
None
"""
configurer(log_name, log_file_path)
while True:
try:
record = queue.get()
if record is None:
break
logger = logging.getLogger(record.name)
logger.handle(record)
except Exception:
print('Failure in listener_process', file=sys.stderr)
traceback.print_last(limit=1, file=sys.stderr)