Debian Codegraph @

pymeasure/log.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26 import logging.handlers
27 from logging.handlers import QueueHandler
28
29 from queue import Queue
30
31 log = logging.getLogger(__name__)
32 log.addHandler(logging.NullHandler())
33
34
35 class QueueListener(logging.handlers.QueueListener):
36 def is_alive(self):
37 try:
38 return self._thread.is_alive()
39 except AttributeError:
40 return False
41
42
43 def console_log(logger, level=logging.INFO, queue=None):
44 """Create a console log handler. Return a scribe thread object."""
45 if queue is None:
46 queue = Queue()
47 logger.setLevel(level)
48 ch = logging.StreamHandler()
49 ch.setLevel(level)
50 formatter = logging.Formatter(
51 fmt='%(asctime)s: %(message)s (%(name)s, %(levelname)s)',
52 datefmt='%I:%M:%S %p')
53 ch.setFormatter(formatter)
54 logger.addHandler(ch)
55 scribe = Scribe(queue)
56 return scribe
57
58
59 def file_log(logger, log_filename, level=logging.INFO, queue=None, **kwargs):
60 """Create a file log handler. Return a scribe thread object."""
61 if queue is None:
62 queue = Queue()
63 logger.setLevel(level)
64 ch = logging.FileHandler(log_filename, **kwargs)
65 ch.setLevel(level)
66 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
67 ch.setFormatter(formatter)
68 logger.addHandler(ch)
69 scribe = Scribe(queue)
70 return scribe
71
72
73 class Scribe(QueueListener):
74 """ Scribe class which logs records as retrieved from a queue to support consistent
75 multi-process logging.
76
77 :param queue: The multiprocessing queue which the scriber will listen to.
78 """
79
80 def __init__(self, queue):
81 super().__init__(queue)
82
83 def handle(self, record):
84 logging.getLogger(record.name).handle(record)
85
86
87 def setup_logging(logger=None, console=False, console_level='INFO', filename=None,
88 file_level='DEBUG', queue=None, file_kwargs=None):
89 """Setup logging for console and/or file logging. Returns a scribe thread object.
90 Defaults to no logging."""
91 if queue is None:
92 queue = Queue()
93 if logger is None:
94 logger = logging.getLogger()
95 if file_kwargs is None:
96 file_kwargs = {}
97
98 logger.handlers = []
99 if console:
100 console_log(logger, level=getattr(logging, console_level))
101 logger.info('Set up console logging')
102 if filename is not None:
103 file_log(logger, filename, level=getattr(logging, file_level), **file_kwargs)
104 logger.info('Set up file logging')
105
106 scribe = Scribe(queue)
107 return scribe
108
109
110 class TopicQueueHandler(QueueHandler):
111 def __init__(self, queue, topic='log'):
112 super().__init__(queue)
113 self.topic = topic
114
115 def prepare(self, record):
116 return self.topic, record