1 | n/a | # Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. |
---|
2 | n/a | # |
---|
3 | n/a | # Permission to use, copy, modify, and distribute this software and its |
---|
4 | n/a | # documentation for any purpose and without fee is hereby granted, |
---|
5 | n/a | # provided that the above copyright notice appear in all copies and that |
---|
6 | n/a | # both that copyright notice and this permission notice appear in |
---|
7 | n/a | # supporting documentation, and that the name of Vinay Sajip |
---|
8 | n/a | # not be used in advertising or publicity pertaining to distribution |
---|
9 | n/a | # of the software without specific, written prior permission. |
---|
10 | n/a | # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING |
---|
11 | n/a | # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL |
---|
12 | n/a | # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR |
---|
13 | n/a | # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER |
---|
14 | n/a | # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT |
---|
15 | n/a | # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
---|
16 | n/a | |
---|
17 | n/a | """ |
---|
18 | n/a | Additional handlers for the logging package for Python. The core package is |
---|
19 | n/a | based on PEP 282 and comments thereto in comp.lang.python. |
---|
20 | n/a | |
---|
21 | n/a | Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved. |
---|
22 | n/a | |
---|
23 | n/a | To use, simply 'import logging.handlers' and log away! |
---|
24 | n/a | """ |
---|
25 | n/a | |
---|
26 | n/a | import logging, socket, os, pickle, struct, time, re |
---|
27 | n/a | from stat import ST_DEV, ST_INO, ST_MTIME |
---|
28 | n/a | import queue |
---|
29 | n/a | try: |
---|
30 | n/a | import threading |
---|
31 | n/a | except ImportError: #pragma: no cover |
---|
32 | n/a | threading = None |
---|
33 | n/a | |
---|
34 | n/a | # |
---|
35 | n/a | # Some constants... |
---|
36 | n/a | # |
---|
37 | n/a | |
---|
38 | n/a | DEFAULT_TCP_LOGGING_PORT = 9020 |
---|
39 | n/a | DEFAULT_UDP_LOGGING_PORT = 9021 |
---|
40 | n/a | DEFAULT_HTTP_LOGGING_PORT = 9022 |
---|
41 | n/a | DEFAULT_SOAP_LOGGING_PORT = 9023 |
---|
42 | n/a | SYSLOG_UDP_PORT = 514 |
---|
43 | n/a | SYSLOG_TCP_PORT = 514 |
---|
44 | n/a | |
---|
45 | n/a | _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day |
---|
46 | n/a | |
---|
47 | n/a | class BaseRotatingHandler(logging.FileHandler): |
---|
48 | n/a | """ |
---|
49 | n/a | Base class for handlers that rotate log files at a certain point. |
---|
50 | n/a | Not meant to be instantiated directly. Instead, use RotatingFileHandler |
---|
51 | n/a | or TimedRotatingFileHandler. |
---|
52 | n/a | """ |
---|
53 | n/a | def __init__(self, filename, mode, encoding=None, delay=False): |
---|
54 | n/a | """ |
---|
55 | n/a | Use the specified filename for streamed logging |
---|
56 | n/a | """ |
---|
57 | n/a | logging.FileHandler.__init__(self, filename, mode, encoding, delay) |
---|
58 | n/a | self.mode = mode |
---|
59 | n/a | self.encoding = encoding |
---|
60 | n/a | self.namer = None |
---|
61 | n/a | self.rotator = None |
---|
62 | n/a | |
---|
63 | n/a | def emit(self, record): |
---|
64 | n/a | """ |
---|
65 | n/a | Emit a record. |
---|
66 | n/a | |
---|
67 | n/a | Output the record to the file, catering for rollover as described |
---|
68 | n/a | in doRollover(). |
---|
69 | n/a | """ |
---|
70 | n/a | try: |
---|
71 | n/a | if self.shouldRollover(record): |
---|
72 | n/a | self.doRollover() |
---|
73 | n/a | logging.FileHandler.emit(self, record) |
---|
74 | n/a | except Exception: |
---|
75 | n/a | self.handleError(record) |
---|
76 | n/a | |
---|
77 | n/a | def rotation_filename(self, default_name): |
---|
78 | n/a | """ |
---|
79 | n/a | Modify the filename of a log file when rotating. |
---|
80 | n/a | |
---|
81 | n/a | This is provided so that a custom filename can be provided. |
---|
82 | n/a | |
---|
83 | n/a | The default implementation calls the 'namer' attribute of the |
---|
84 | n/a | handler, if it's callable, passing the default name to |
---|
85 | n/a | it. If the attribute isn't callable (the default is None), the name |
---|
86 | n/a | is returned unchanged. |
---|
87 | n/a | |
---|
88 | n/a | :param default_name: The default name for the log file. |
---|
89 | n/a | """ |
---|
90 | n/a | if not callable(self.namer): |
---|
91 | n/a | result = default_name |
---|
92 | n/a | else: |
---|
93 | n/a | result = self.namer(default_name) |
---|
94 | n/a | return result |
---|
95 | n/a | |
---|
96 | n/a | def rotate(self, source, dest): |
---|
97 | n/a | """ |
---|
98 | n/a | When rotating, rotate the current log. |
---|
99 | n/a | |
---|
100 | n/a | The default implementation calls the 'rotator' attribute of the |
---|
101 | n/a | handler, if it's callable, passing the source and dest arguments to |
---|
102 | n/a | it. If the attribute isn't callable (the default is None), the source |
---|
103 | n/a | is simply renamed to the destination. |
---|
104 | n/a | |
---|
105 | n/a | :param source: The source filename. This is normally the base |
---|
106 | n/a | filename, e.g. 'test.log' |
---|
107 | n/a | :param dest: The destination filename. This is normally |
---|
108 | n/a | what the source is rotated to, e.g. 'test.log.1'. |
---|
109 | n/a | """ |
---|
110 | n/a | if not callable(self.rotator): |
---|
111 | n/a | # Issue 18940: A file may not have been created if delay is True. |
---|
112 | n/a | if os.path.exists(source): |
---|
113 | n/a | os.rename(source, dest) |
---|
114 | n/a | else: |
---|
115 | n/a | self.rotator(source, dest) |
---|
116 | n/a | |
---|
117 | n/a | class RotatingFileHandler(BaseRotatingHandler): |
---|
118 | n/a | """ |
---|
119 | n/a | Handler for logging to a set of files, which switches from one file |
---|
120 | n/a | to the next when the current file reaches a certain size. |
---|
121 | n/a | """ |
---|
122 | n/a | def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): |
---|
123 | n/a | """ |
---|
124 | n/a | Open the specified file and use it as the stream for logging. |
---|
125 | n/a | |
---|
126 | n/a | By default, the file grows indefinitely. You can specify particular |
---|
127 | n/a | values of maxBytes and backupCount to allow the file to rollover at |
---|
128 | n/a | a predetermined size. |
---|
129 | n/a | |
---|
130 | n/a | Rollover occurs whenever the current log file is nearly maxBytes in |
---|
131 | n/a | length. If backupCount is >= 1, the system will successively create |
---|
132 | n/a | new files with the same pathname as the base file, but with extensions |
---|
133 | n/a | ".1", ".2" etc. appended to it. For example, with a backupCount of 5 |
---|
134 | n/a | and a base file name of "app.log", you would get "app.log", |
---|
135 | n/a | "app.log.1", "app.log.2", ... through to "app.log.5". The file being |
---|
136 | n/a | written to is always "app.log" - when it gets filled up, it is closed |
---|
137 | n/a | and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. |
---|
138 | n/a | exist, then they are renamed to "app.log.2", "app.log.3" etc. |
---|
139 | n/a | respectively. |
---|
140 | n/a | |
---|
141 | n/a | If maxBytes is zero, rollover never occurs. |
---|
142 | n/a | """ |
---|
143 | n/a | # If rotation/rollover is wanted, it doesn't make sense to use another |
---|
144 | n/a | # mode. If for example 'w' were specified, then if there were multiple |
---|
145 | n/a | # runs of the calling application, the logs from previous runs would be |
---|
146 | n/a | # lost if the 'w' is respected, because the log file would be truncated |
---|
147 | n/a | # on each run. |
---|
148 | n/a | if maxBytes > 0: |
---|
149 | n/a | mode = 'a' |
---|
150 | n/a | BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) |
---|
151 | n/a | self.maxBytes = maxBytes |
---|
152 | n/a | self.backupCount = backupCount |
---|
153 | n/a | |
---|
154 | n/a | def doRollover(self): |
---|
155 | n/a | """ |
---|
156 | n/a | Do a rollover, as described in __init__(). |
---|
157 | n/a | """ |
---|
158 | n/a | if self.stream: |
---|
159 | n/a | self.stream.close() |
---|
160 | n/a | self.stream = None |
---|
161 | n/a | if self.backupCount > 0: |
---|
162 | n/a | for i in range(self.backupCount - 1, 0, -1): |
---|
163 | n/a | sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i)) |
---|
164 | n/a | dfn = self.rotation_filename("%s.%d" % (self.baseFilename, |
---|
165 | n/a | i + 1)) |
---|
166 | n/a | if os.path.exists(sfn): |
---|
167 | n/a | if os.path.exists(dfn): |
---|
168 | n/a | os.remove(dfn) |
---|
169 | n/a | os.rename(sfn, dfn) |
---|
170 | n/a | dfn = self.rotation_filename(self.baseFilename + ".1") |
---|
171 | n/a | if os.path.exists(dfn): |
---|
172 | n/a | os.remove(dfn) |
---|
173 | n/a | self.rotate(self.baseFilename, dfn) |
---|
174 | n/a | if not self.delay: |
---|
175 | n/a | self.stream = self._open() |
---|
176 | n/a | |
---|
177 | n/a | def shouldRollover(self, record): |
---|
178 | n/a | """ |
---|
179 | n/a | Determine if rollover should occur. |
---|
180 | n/a | |
---|
181 | n/a | Basically, see if the supplied record would cause the file to exceed |
---|
182 | n/a | the size limit we have. |
---|
183 | n/a | """ |
---|
184 | n/a | if self.stream is None: # delay was set... |
---|
185 | n/a | self.stream = self._open() |
---|
186 | n/a | if self.maxBytes > 0: # are we rolling over? |
---|
187 | n/a | msg = "%s\n" % self.format(record) |
---|
188 | n/a | self.stream.seek(0, 2) #due to non-posix-compliant Windows feature |
---|
189 | n/a | if self.stream.tell() + len(msg) >= self.maxBytes: |
---|
190 | n/a | return 1 |
---|
191 | n/a | return 0 |
---|
192 | n/a | |
---|
193 | n/a | class TimedRotatingFileHandler(BaseRotatingHandler): |
---|
194 | n/a | """ |
---|
195 | n/a | Handler for logging to a file, rotating the log file at certain timed |
---|
196 | n/a | intervals. |
---|
197 | n/a | |
---|
198 | n/a | If backupCount is > 0, when rollover is done, no more than backupCount |
---|
199 | n/a | files are kept - the oldest ones are deleted. |
---|
200 | n/a | """ |
---|
201 | n/a | def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None): |
---|
202 | n/a | BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) |
---|
203 | n/a | self.when = when.upper() |
---|
204 | n/a | self.backupCount = backupCount |
---|
205 | n/a | self.utc = utc |
---|
206 | n/a | self.atTime = atTime |
---|
207 | n/a | # Calculate the real rollover interval, which is just the number of |
---|
208 | n/a | # seconds between rollovers. Also set the filename suffix used when |
---|
209 | n/a | # a rollover occurs. Current 'when' events supported: |
---|
210 | n/a | # S - Seconds |
---|
211 | n/a | # M - Minutes |
---|
212 | n/a | # H - Hours |
---|
213 | n/a | # D - Days |
---|
214 | n/a | # midnight - roll over at midnight |
---|
215 | n/a | # W{0-6} - roll over on a certain day; 0 - Monday |
---|
216 | n/a | # |
---|
217 | n/a | # Case of the 'when' specifier is not important; lower or upper case |
---|
218 | n/a | # will work. |
---|
219 | n/a | if self.when == 'S': |
---|
220 | n/a | self.interval = 1 # one second |
---|
221 | n/a | self.suffix = "%Y-%m-%d_%H-%M-%S" |
---|
222 | n/a | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$" |
---|
223 | n/a | elif self.when == 'M': |
---|
224 | n/a | self.interval = 60 # one minute |
---|
225 | n/a | self.suffix = "%Y-%m-%d_%H-%M" |
---|
226 | n/a | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$" |
---|
227 | n/a | elif self.when == 'H': |
---|
228 | n/a | self.interval = 60 * 60 # one hour |
---|
229 | n/a | self.suffix = "%Y-%m-%d_%H" |
---|
230 | n/a | self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$" |
---|
231 | n/a | elif self.when == 'D' or self.when == 'MIDNIGHT': |
---|
232 | n/a | self.interval = 60 * 60 * 24 # one day |
---|
233 | n/a | self.suffix = "%Y-%m-%d" |
---|
234 | n/a | self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" |
---|
235 | n/a | elif self.when.startswith('W'): |
---|
236 | n/a | self.interval = 60 * 60 * 24 * 7 # one week |
---|
237 | n/a | if len(self.when) != 2: |
---|
238 | n/a | raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) |
---|
239 | n/a | if self.when[1] < '0' or self.when[1] > '6': |
---|
240 | n/a | raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) |
---|
241 | n/a | self.dayOfWeek = int(self.when[1]) |
---|
242 | n/a | self.suffix = "%Y-%m-%d" |
---|
243 | n/a | self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" |
---|
244 | n/a | else: |
---|
245 | n/a | raise ValueError("Invalid rollover interval specified: %s" % self.when) |
---|
246 | n/a | |
---|
247 | n/a | self.extMatch = re.compile(self.extMatch, re.ASCII) |
---|
248 | n/a | self.interval = self.interval * interval # multiply by units requested |
---|
249 | n/a | # The following line added because the filename passed in could be a |
---|
250 | n/a | # path object (see Issue #27493), but self.baseFilename will be a string |
---|
251 | n/a | filename = self.baseFilename |
---|
252 | n/a | if os.path.exists(filename): |
---|
253 | n/a | t = os.stat(filename)[ST_MTIME] |
---|
254 | n/a | else: |
---|
255 | n/a | t = int(time.time()) |
---|
256 | n/a | self.rolloverAt = self.computeRollover(t) |
---|
257 | n/a | |
---|
258 | n/a | def computeRollover(self, currentTime): |
---|
259 | n/a | """ |
---|
260 | n/a | Work out the rollover time based on the specified time. |
---|
261 | n/a | """ |
---|
262 | n/a | result = currentTime + self.interval |
---|
263 | n/a | # If we are rolling over at midnight or weekly, then the interval is already known. |
---|
264 | n/a | # What we need to figure out is WHEN the next interval is. In other words, |
---|
265 | n/a | # if you are rolling over at midnight, then your base interval is 1 day, |
---|
266 | n/a | # but you want to start that one day clock at midnight, not now. So, we |
---|
267 | n/a | # have to fudge the rolloverAt value in order to trigger the first rollover |
---|
268 | n/a | # at the right time. After that, the regular interval will take care of |
---|
269 | n/a | # the rest. Note that this code doesn't care about leap seconds. :) |
---|
270 | n/a | if self.when == 'MIDNIGHT' or self.when.startswith('W'): |
---|
271 | n/a | # This could be done with less code, but I wanted it to be clear |
---|
272 | n/a | if self.utc: |
---|
273 | n/a | t = time.gmtime(currentTime) |
---|
274 | n/a | else: |
---|
275 | n/a | t = time.localtime(currentTime) |
---|
276 | n/a | currentHour = t[3] |
---|
277 | n/a | currentMinute = t[4] |
---|
278 | n/a | currentSecond = t[5] |
---|
279 | n/a | currentDay = t[6] |
---|
280 | n/a | # r is the number of seconds left between now and the next rotation |
---|
281 | n/a | if self.atTime is None: |
---|
282 | n/a | rotate_ts = _MIDNIGHT |
---|
283 | n/a | else: |
---|
284 | n/a | rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 + |
---|
285 | n/a | self.atTime.second) |
---|
286 | n/a | |
---|
287 | n/a | r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 + |
---|
288 | n/a | currentSecond) |
---|
289 | n/a | if r < 0: |
---|
290 | n/a | # Rotate time is before the current time (for example when |
---|
291 | n/a | # self.rotateAt is 13:45 and it now 14:15), rotation is |
---|
292 | n/a | # tomorrow. |
---|
293 | n/a | r += _MIDNIGHT |
---|
294 | n/a | currentDay = (currentDay + 1) % 7 |
---|
295 | n/a | result = currentTime + r |
---|
296 | n/a | # If we are rolling over on a certain day, add in the number of days until |
---|
297 | n/a | # the next rollover, but offset by 1 since we just calculated the time |
---|
298 | n/a | # until the next day starts. There are three cases: |
---|
299 | n/a | # Case 1) The day to rollover is today; in this case, do nothing |
---|
300 | n/a | # Case 2) The day to rollover is further in the interval (i.e., today is |
---|
301 | n/a | # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to |
---|
302 | n/a | # next rollover is simply 6 - 2 - 1, or 3. |
---|
303 | n/a | # Case 3) The day to rollover is behind us in the interval (i.e., today |
---|
304 | n/a | # is day 5 (Saturday) and rollover is on day 3 (Thursday). |
---|
305 | n/a | # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the |
---|
306 | n/a | # number of days left in the current week (1) plus the number |
---|
307 | n/a | # of days in the next week until the rollover day (3). |
---|
308 | n/a | # The calculations described in 2) and 3) above need to have a day added. |
---|
309 | n/a | # This is because the above time calculation takes us to midnight on this |
---|
310 | n/a | # day, i.e. the start of the next day. |
---|
311 | n/a | if self.when.startswith('W'): |
---|
312 | n/a | day = currentDay # 0 is Monday |
---|
313 | n/a | if day != self.dayOfWeek: |
---|
314 | n/a | if day < self.dayOfWeek: |
---|
315 | n/a | daysToWait = self.dayOfWeek - day |
---|
316 | n/a | else: |
---|
317 | n/a | daysToWait = 6 - day + self.dayOfWeek + 1 |
---|
318 | n/a | newRolloverAt = result + (daysToWait * (60 * 60 * 24)) |
---|
319 | n/a | if not self.utc: |
---|
320 | n/a | dstNow = t[-1] |
---|
321 | n/a | dstAtRollover = time.localtime(newRolloverAt)[-1] |
---|
322 | n/a | if dstNow != dstAtRollover: |
---|
323 | n/a | if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour |
---|
324 | n/a | addend = -3600 |
---|
325 | n/a | else: # DST bows out before next rollover, so we need to add an hour |
---|
326 | n/a | addend = 3600 |
---|
327 | n/a | newRolloverAt += addend |
---|
328 | n/a | result = newRolloverAt |
---|
329 | n/a | return result |
---|
330 | n/a | |
---|
331 | n/a | def shouldRollover(self, record): |
---|
332 | n/a | """ |
---|
333 | n/a | Determine if rollover should occur. |
---|
334 | n/a | |
---|
335 | n/a | record is not used, as we are just comparing times, but it is needed so |
---|
336 | n/a | the method signatures are the same |
---|
337 | n/a | """ |
---|
338 | n/a | t = int(time.time()) |
---|
339 | n/a | if t >= self.rolloverAt: |
---|
340 | n/a | return 1 |
---|
341 | n/a | return 0 |
---|
342 | n/a | |
---|
343 | n/a | def getFilesToDelete(self): |
---|
344 | n/a | """ |
---|
345 | n/a | Determine the files to delete when rolling over. |
---|
346 | n/a | |
---|
347 | n/a | More specific than the earlier method, which just used glob.glob(). |
---|
348 | n/a | """ |
---|
349 | n/a | dirName, baseName = os.path.split(self.baseFilename) |
---|
350 | n/a | fileNames = os.listdir(dirName) |
---|
351 | n/a | result = [] |
---|
352 | n/a | prefix = baseName + "." |
---|
353 | n/a | plen = len(prefix) |
---|
354 | n/a | for fileName in fileNames: |
---|
355 | n/a | if fileName[:plen] == prefix: |
---|
356 | n/a | suffix = fileName[plen:] |
---|
357 | n/a | if self.extMatch.match(suffix): |
---|
358 | n/a | result.append(os.path.join(dirName, fileName)) |
---|
359 | n/a | result.sort() |
---|
360 | n/a | if len(result) < self.backupCount: |
---|
361 | n/a | result = [] |
---|
362 | n/a | else: |
---|
363 | n/a | result = result[:len(result) - self.backupCount] |
---|
364 | n/a | return result |
---|
365 | n/a | |
---|
366 | n/a | def doRollover(self): |
---|
367 | n/a | """ |
---|
368 | n/a | do a rollover; in this case, a date/time stamp is appended to the filename |
---|
369 | n/a | when the rollover happens. However, you want the file to be named for the |
---|
370 | n/a | start of the interval, not the current time. If there is a backup count, |
---|
371 | n/a | then we have to get a list of matching filenames, sort them and remove |
---|
372 | n/a | the one with the oldest suffix. |
---|
373 | n/a | """ |
---|
374 | n/a | if self.stream: |
---|
375 | n/a | self.stream.close() |
---|
376 | n/a | self.stream = None |
---|
377 | n/a | # get the time that this sequence started at and make it a TimeTuple |
---|
378 | n/a | currentTime = int(time.time()) |
---|
379 | n/a | dstNow = time.localtime(currentTime)[-1] |
---|
380 | n/a | t = self.rolloverAt - self.interval |
---|
381 | n/a | if self.utc: |
---|
382 | n/a | timeTuple = time.gmtime(t) |
---|
383 | n/a | else: |
---|
384 | n/a | timeTuple = time.localtime(t) |
---|
385 | n/a | dstThen = timeTuple[-1] |
---|
386 | n/a | if dstNow != dstThen: |
---|
387 | n/a | if dstNow: |
---|
388 | n/a | addend = 3600 |
---|
389 | n/a | else: |
---|
390 | n/a | addend = -3600 |
---|
391 | n/a | timeTuple = time.localtime(t + addend) |
---|
392 | n/a | dfn = self.rotation_filename(self.baseFilename + "." + |
---|
393 | n/a | time.strftime(self.suffix, timeTuple)) |
---|
394 | n/a | if os.path.exists(dfn): |
---|
395 | n/a | os.remove(dfn) |
---|
396 | n/a | self.rotate(self.baseFilename, dfn) |
---|
397 | n/a | if self.backupCount > 0: |
---|
398 | n/a | for s in self.getFilesToDelete(): |
---|
399 | n/a | os.remove(s) |
---|
400 | n/a | if not self.delay: |
---|
401 | n/a | self.stream = self._open() |
---|
402 | n/a | newRolloverAt = self.computeRollover(currentTime) |
---|
403 | n/a | while newRolloverAt <= currentTime: |
---|
404 | n/a | newRolloverAt = newRolloverAt + self.interval |
---|
405 | n/a | #If DST changes and midnight or weekly rollover, adjust for this. |
---|
406 | n/a | if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: |
---|
407 | n/a | dstAtRollover = time.localtime(newRolloverAt)[-1] |
---|
408 | n/a | if dstNow != dstAtRollover: |
---|
409 | n/a | if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour |
---|
410 | n/a | addend = -3600 |
---|
411 | n/a | else: # DST bows out before next rollover, so we need to add an hour |
---|
412 | n/a | addend = 3600 |
---|
413 | n/a | newRolloverAt += addend |
---|
414 | n/a | self.rolloverAt = newRolloverAt |
---|
415 | n/a | |
---|
416 | n/a | class WatchedFileHandler(logging.FileHandler): |
---|
417 | n/a | """ |
---|
418 | n/a | A handler for logging to a file, which watches the file |
---|
419 | n/a | to see if it has changed while in use. This can happen because of |
---|
420 | n/a | usage of programs such as newsyslog and logrotate which perform |
---|
421 | n/a | log file rotation. This handler, intended for use under Unix, |
---|
422 | n/a | watches the file to see if it has changed since the last emit. |
---|
423 | n/a | (A file has changed if its device or inode have changed.) |
---|
424 | n/a | If it has changed, the old file stream is closed, and the file |
---|
425 | n/a | opened to get a new stream. |
---|
426 | n/a | |
---|
427 | n/a | This handler is not appropriate for use under Windows, because |
---|
428 | n/a | under Windows open files cannot be moved or renamed - logging |
---|
429 | n/a | opens the files with exclusive locks - and so there is no need |
---|
430 | n/a | for such a handler. Furthermore, ST_INO is not supported under |
---|
431 | n/a | Windows; stat always returns zero for this value. |
---|
432 | n/a | |
---|
433 | n/a | This handler is based on a suggestion and patch by Chad J. |
---|
434 | n/a | Schroeder. |
---|
435 | n/a | """ |
---|
436 | n/a | def __init__(self, filename, mode='a', encoding=None, delay=False): |
---|
437 | n/a | logging.FileHandler.__init__(self, filename, mode, encoding, delay) |
---|
438 | n/a | self.dev, self.ino = -1, -1 |
---|
439 | n/a | self._statstream() |
---|
440 | n/a | |
---|
441 | n/a | def _statstream(self): |
---|
442 | n/a | if self.stream: |
---|
443 | n/a | sres = os.fstat(self.stream.fileno()) |
---|
444 | n/a | self.dev, self.ino = sres[ST_DEV], sres[ST_INO] |
---|
445 | n/a | |
---|
446 | n/a | def reopenIfNeeded(self): |
---|
447 | n/a | """ |
---|
448 | n/a | Reopen log file if needed. |
---|
449 | n/a | |
---|
450 | n/a | Checks if the underlying file has changed, and if it |
---|
451 | n/a | has, close the old stream and reopen the file to get the |
---|
452 | n/a | current stream. |
---|
453 | n/a | """ |
---|
454 | n/a | # Reduce the chance of race conditions by stat'ing by path only |
---|
455 | n/a | # once and then fstat'ing our new fd if we opened a new log stream. |
---|
456 | n/a | # See issue #14632: Thanks to John Mulligan for the problem report |
---|
457 | n/a | # and patch. |
---|
458 | n/a | try: |
---|
459 | n/a | # stat the file by path, checking for existence |
---|
460 | n/a | sres = os.stat(self.baseFilename) |
---|
461 | n/a | except FileNotFoundError: |
---|
462 | n/a | sres = None |
---|
463 | n/a | # compare file system stat with that of our stream file handle |
---|
464 | n/a | if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: |
---|
465 | n/a | if self.stream is not None: |
---|
466 | n/a | # we have an open file handle, clean it up |
---|
467 | n/a | self.stream.flush() |
---|
468 | n/a | self.stream.close() |
---|
469 | n/a | self.stream = None # See Issue #21742: _open () might fail. |
---|
470 | n/a | # open a new file handle and get new stat info from that fd |
---|
471 | n/a | self.stream = self._open() |
---|
472 | n/a | self._statstream() |
---|
473 | n/a | |
---|
474 | n/a | def emit(self, record): |
---|
475 | n/a | """ |
---|
476 | n/a | Emit a record. |
---|
477 | n/a | |
---|
478 | n/a | If underlying file has changed, reopen the file before emitting the |
---|
479 | n/a | record to it. |
---|
480 | n/a | """ |
---|
481 | n/a | self.reopenIfNeeded() |
---|
482 | n/a | logging.FileHandler.emit(self, record) |
---|
483 | n/a | |
---|
484 | n/a | |
---|
485 | n/a | class SocketHandler(logging.Handler): |
---|
486 | n/a | """ |
---|
487 | n/a | A handler class which writes logging records, in pickle format, to |
---|
488 | n/a | a streaming socket. The socket is kept open across logging calls. |
---|
489 | n/a | If the peer resets it, an attempt is made to reconnect on the next call. |
---|
490 | n/a | The pickle which is sent is that of the LogRecord's attribute dictionary |
---|
491 | n/a | (__dict__), so that the receiver does not need to have the logging module |
---|
492 | n/a | installed in order to process the logging event. |
---|
493 | n/a | |
---|
494 | n/a | To unpickle the record at the receiving end into a LogRecord, use the |
---|
495 | n/a | makeLogRecord function. |
---|
496 | n/a | """ |
---|
497 | n/a | |
---|
498 | n/a | def __init__(self, host, port): |
---|
499 | n/a | """ |
---|
500 | n/a | Initializes the handler with a specific host address and port. |
---|
501 | n/a | |
---|
502 | n/a | When the attribute *closeOnError* is set to True - if a socket error |
---|
503 | n/a | occurs, the socket is silently closed and then reopened on the next |
---|
504 | n/a | logging call. |
---|
505 | n/a | """ |
---|
506 | n/a | logging.Handler.__init__(self) |
---|
507 | n/a | self.host = host |
---|
508 | n/a | self.port = port |
---|
509 | n/a | if port is None: |
---|
510 | n/a | self.address = host |
---|
511 | n/a | else: |
---|
512 | n/a | self.address = (host, port) |
---|
513 | n/a | self.sock = None |
---|
514 | n/a | self.closeOnError = False |
---|
515 | n/a | self.retryTime = None |
---|
516 | n/a | # |
---|
517 | n/a | # Exponential backoff parameters. |
---|
518 | n/a | # |
---|
519 | n/a | self.retryStart = 1.0 |
---|
520 | n/a | self.retryMax = 30.0 |
---|
521 | n/a | self.retryFactor = 2.0 |
---|
522 | n/a | |
---|
523 | n/a | def makeSocket(self, timeout=1): |
---|
524 | n/a | """ |
---|
525 | n/a | A factory method which allows subclasses to define the precise |
---|
526 | n/a | type of socket they want. |
---|
527 | n/a | """ |
---|
528 | n/a | if self.port is not None: |
---|
529 | n/a | result = socket.create_connection(self.address, timeout=timeout) |
---|
530 | n/a | else: |
---|
531 | n/a | result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
---|
532 | n/a | result.settimeout(timeout) |
---|
533 | n/a | try: |
---|
534 | n/a | result.connect(self.address) |
---|
535 | n/a | except OSError: |
---|
536 | n/a | result.close() # Issue 19182 |
---|
537 | n/a | raise |
---|
538 | n/a | return result |
---|
539 | n/a | |
---|
540 | n/a | def createSocket(self): |
---|
541 | n/a | """ |
---|
542 | n/a | Try to create a socket, using an exponential backoff with |
---|
543 | n/a | a max retry time. Thanks to Robert Olson for the original patch |
---|
544 | n/a | (SF #815911) which has been slightly refactored. |
---|
545 | n/a | """ |
---|
546 | n/a | now = time.time() |
---|
547 | n/a | # Either retryTime is None, in which case this |
---|
548 | n/a | # is the first time back after a disconnect, or |
---|
549 | n/a | # we've waited long enough. |
---|
550 | n/a | if self.retryTime is None: |
---|
551 | n/a | attempt = True |
---|
552 | n/a | else: |
---|
553 | n/a | attempt = (now >= self.retryTime) |
---|
554 | n/a | if attempt: |
---|
555 | n/a | try: |
---|
556 | n/a | self.sock = self.makeSocket() |
---|
557 | n/a | self.retryTime = None # next time, no delay before trying |
---|
558 | n/a | except OSError: |
---|
559 | n/a | #Creation failed, so set the retry time and return. |
---|
560 | n/a | if self.retryTime is None: |
---|
561 | n/a | self.retryPeriod = self.retryStart |
---|
562 | n/a | else: |
---|
563 | n/a | self.retryPeriod = self.retryPeriod * self.retryFactor |
---|
564 | n/a | if self.retryPeriod > self.retryMax: |
---|
565 | n/a | self.retryPeriod = self.retryMax |
---|
566 | n/a | self.retryTime = now + self.retryPeriod |
---|
567 | n/a | |
---|
568 | n/a | def send(self, s): |
---|
569 | n/a | """ |
---|
570 | n/a | Send a pickled string to the socket. |
---|
571 | n/a | |
---|
572 | n/a | This function allows for partial sends which can happen when the |
---|
573 | n/a | network is busy. |
---|
574 | n/a | """ |
---|
575 | n/a | if self.sock is None: |
---|
576 | n/a | self.createSocket() |
---|
577 | n/a | #self.sock can be None either because we haven't reached the retry |
---|
578 | n/a | #time yet, or because we have reached the retry time and retried, |
---|
579 | n/a | #but are still unable to connect. |
---|
580 | n/a | if self.sock: |
---|
581 | n/a | try: |
---|
582 | n/a | self.sock.sendall(s) |
---|
583 | n/a | except OSError: #pragma: no cover |
---|
584 | n/a | self.sock.close() |
---|
585 | n/a | self.sock = None # so we can call createSocket next time |
---|
586 | n/a | |
---|
587 | n/a | def makePickle(self, record): |
---|
588 | n/a | """ |
---|
589 | n/a | Pickles the record in binary format with a length prefix, and |
---|
590 | n/a | returns it ready for transmission across the socket. |
---|
591 | n/a | """ |
---|
592 | n/a | ei = record.exc_info |
---|
593 | n/a | if ei: |
---|
594 | n/a | # just to get traceback text into record.exc_text ... |
---|
595 | n/a | dummy = self.format(record) |
---|
596 | n/a | # See issue #14436: If msg or args are objects, they may not be |
---|
597 | n/a | # available on the receiving end. So we convert the msg % args |
---|
598 | n/a | # to a string, save it as msg and zap the args. |
---|
599 | n/a | d = dict(record.__dict__) |
---|
600 | n/a | d['msg'] = record.getMessage() |
---|
601 | n/a | d['args'] = None |
---|
602 | n/a | d['exc_info'] = None |
---|
603 | n/a | # Issue #25685: delete 'message' if present: redundant with 'msg' |
---|
604 | n/a | d.pop('message', None) |
---|
605 | n/a | s = pickle.dumps(d, 1) |
---|
606 | n/a | slen = struct.pack(">L", len(s)) |
---|
607 | n/a | return slen + s |
---|
608 | n/a | |
---|
609 | n/a | def handleError(self, record): |
---|
610 | n/a | """ |
---|
611 | n/a | Handle an error during logging. |
---|
612 | n/a | |
---|
613 | n/a | An error has occurred during logging. Most likely cause - |
---|
614 | n/a | connection lost. Close the socket so that we can retry on the |
---|
615 | n/a | next event. |
---|
616 | n/a | """ |
---|
617 | n/a | if self.closeOnError and self.sock: |
---|
618 | n/a | self.sock.close() |
---|
619 | n/a | self.sock = None #try to reconnect next time |
---|
620 | n/a | else: |
---|
621 | n/a | logging.Handler.handleError(self, record) |
---|
622 | n/a | |
---|
623 | n/a | def emit(self, record): |
---|
624 | n/a | """ |
---|
625 | n/a | Emit a record. |
---|
626 | n/a | |
---|
627 | n/a | Pickles the record and writes it to the socket in binary format. |
---|
628 | n/a | If there is an error with the socket, silently drop the packet. |
---|
629 | n/a | If there was a problem with the socket, re-establishes the |
---|
630 | n/a | socket. |
---|
631 | n/a | """ |
---|
632 | n/a | try: |
---|
633 | n/a | s = self.makePickle(record) |
---|
634 | n/a | self.send(s) |
---|
635 | n/a | except Exception: |
---|
636 | n/a | self.handleError(record) |
---|
637 | n/a | |
---|
638 | n/a | def close(self): |
---|
639 | n/a | """ |
---|
640 | n/a | Closes the socket. |
---|
641 | n/a | """ |
---|
642 | n/a | self.acquire() |
---|
643 | n/a | try: |
---|
644 | n/a | sock = self.sock |
---|
645 | n/a | if sock: |
---|
646 | n/a | self.sock = None |
---|
647 | n/a | sock.close() |
---|
648 | n/a | logging.Handler.close(self) |
---|
649 | n/a | finally: |
---|
650 | n/a | self.release() |
---|
651 | n/a | |
---|
652 | n/a | class DatagramHandler(SocketHandler): |
---|
653 | n/a | """ |
---|
654 | n/a | A handler class which writes logging records, in pickle format, to |
---|
655 | n/a | a datagram socket. The pickle which is sent is that of the LogRecord's |
---|
656 | n/a | attribute dictionary (__dict__), so that the receiver does not need to |
---|
657 | n/a | have the logging module installed in order to process the logging event. |
---|
658 | n/a | |
---|
659 | n/a | To unpickle the record at the receiving end into a LogRecord, use the |
---|
660 | n/a | makeLogRecord function. |
---|
661 | n/a | |
---|
662 | n/a | """ |
---|
663 | n/a | def __init__(self, host, port): |
---|
664 | n/a | """ |
---|
665 | n/a | Initializes the handler with a specific host address and port. |
---|
666 | n/a | """ |
---|
667 | n/a | SocketHandler.__init__(self, host, port) |
---|
668 | n/a | self.closeOnError = False |
---|
669 | n/a | |
---|
670 | n/a | def makeSocket(self): |
---|
671 | n/a | """ |
---|
672 | n/a | The factory method of SocketHandler is here overridden to create |
---|
673 | n/a | a UDP socket (SOCK_DGRAM). |
---|
674 | n/a | """ |
---|
675 | n/a | if self.port is None: |
---|
676 | n/a | family = socket.AF_UNIX |
---|
677 | n/a | else: |
---|
678 | n/a | family = socket.AF_INET |
---|
679 | n/a | s = socket.socket(family, socket.SOCK_DGRAM) |
---|
680 | n/a | return s |
---|
681 | n/a | |
---|
682 | n/a | def send(self, s): |
---|
683 | n/a | """ |
---|
684 | n/a | Send a pickled string to a socket. |
---|
685 | n/a | |
---|
686 | n/a | This function no longer allows for partial sends which can happen |
---|
687 | n/a | when the network is busy - UDP does not guarantee delivery and |
---|
688 | n/a | can deliver packets out of sequence. |
---|
689 | n/a | """ |
---|
690 | n/a | if self.sock is None: |
---|
691 | n/a | self.createSocket() |
---|
692 | n/a | self.sock.sendto(s, self.address) |
---|
693 | n/a | |
---|
694 | n/a | class SysLogHandler(logging.Handler): |
---|
695 | n/a | """ |
---|
696 | n/a | A handler class which sends formatted logging records to a syslog |
---|
697 | n/a | server. Based on Sam Rushing's syslog module: |
---|
698 | n/a | http://www.nightmare.com/squirl/python-ext/misc/syslog.py |
---|
699 | n/a | Contributed by Nicolas Untz (after which minor refactoring changes |
---|
700 | n/a | have been made). |
---|
701 | n/a | """ |
---|
702 | n/a | |
---|
703 | n/a | # from <linux/sys/syslog.h>: |
---|
704 | n/a | # ====================================================================== |
---|
705 | n/a | # priorities/facilities are encoded into a single 32-bit quantity, where |
---|
706 | n/a | # the bottom 3 bits are the priority (0-7) and the top 28 bits are the |
---|
707 | n/a | # facility (0-big number). Both the priorities and the facilities map |
---|
708 | n/a | # roughly one-to-one to strings in the syslogd(8) source code. This |
---|
709 | n/a | # mapping is included in this file. |
---|
710 | n/a | # |
---|
711 | n/a | # priorities (these are ordered) |
---|
712 | n/a | |
---|
713 | n/a | LOG_EMERG = 0 # system is unusable |
---|
714 | n/a | LOG_ALERT = 1 # action must be taken immediately |
---|
715 | n/a | LOG_CRIT = 2 # critical conditions |
---|
716 | n/a | LOG_ERR = 3 # error conditions |
---|
717 | n/a | LOG_WARNING = 4 # warning conditions |
---|
718 | n/a | LOG_NOTICE = 5 # normal but significant condition |
---|
719 | n/a | LOG_INFO = 6 # informational |
---|
720 | n/a | LOG_DEBUG = 7 # debug-level messages |
---|
721 | n/a | |
---|
722 | n/a | # facility codes |
---|
723 | n/a | LOG_KERN = 0 # kernel messages |
---|
724 | n/a | LOG_USER = 1 # random user-level messages |
---|
725 | n/a | LOG_MAIL = 2 # mail system |
---|
726 | n/a | LOG_DAEMON = 3 # system daemons |
---|
727 | n/a | LOG_AUTH = 4 # security/authorization messages |
---|
728 | n/a | LOG_SYSLOG = 5 # messages generated internally by syslogd |
---|
729 | n/a | LOG_LPR = 6 # line printer subsystem |
---|
730 | n/a | LOG_NEWS = 7 # network news subsystem |
---|
731 | n/a | LOG_UUCP = 8 # UUCP subsystem |
---|
732 | n/a | LOG_CRON = 9 # clock daemon |
---|
733 | n/a | LOG_AUTHPRIV = 10 # security/authorization messages (private) |
---|
734 | n/a | LOG_FTP = 11 # FTP daemon |
---|
735 | n/a | |
---|
736 | n/a | # other codes through 15 reserved for system use |
---|
737 | n/a | LOG_LOCAL0 = 16 # reserved for local use |
---|
738 | n/a | LOG_LOCAL1 = 17 # reserved for local use |
---|
739 | n/a | LOG_LOCAL2 = 18 # reserved for local use |
---|
740 | n/a | LOG_LOCAL3 = 19 # reserved for local use |
---|
741 | n/a | LOG_LOCAL4 = 20 # reserved for local use |
---|
742 | n/a | LOG_LOCAL5 = 21 # reserved for local use |
---|
743 | n/a | LOG_LOCAL6 = 22 # reserved for local use |
---|
744 | n/a | LOG_LOCAL7 = 23 # reserved for local use |
---|
745 | n/a | |
---|
746 | n/a | priority_names = { |
---|
747 | n/a | "alert": LOG_ALERT, |
---|
748 | n/a | "crit": LOG_CRIT, |
---|
749 | n/a | "critical": LOG_CRIT, |
---|
750 | n/a | "debug": LOG_DEBUG, |
---|
751 | n/a | "emerg": LOG_EMERG, |
---|
752 | n/a | "err": LOG_ERR, |
---|
753 | n/a | "error": LOG_ERR, # DEPRECATED |
---|
754 | n/a | "info": LOG_INFO, |
---|
755 | n/a | "notice": LOG_NOTICE, |
---|
756 | n/a | "panic": LOG_EMERG, # DEPRECATED |
---|
757 | n/a | "warn": LOG_WARNING, # DEPRECATED |
---|
758 | n/a | "warning": LOG_WARNING, |
---|
759 | n/a | } |
---|
760 | n/a | |
---|
761 | n/a | facility_names = { |
---|
762 | n/a | "auth": LOG_AUTH, |
---|
763 | n/a | "authpriv": LOG_AUTHPRIV, |
---|
764 | n/a | "cron": LOG_CRON, |
---|
765 | n/a | "daemon": LOG_DAEMON, |
---|
766 | n/a | "ftp": LOG_FTP, |
---|
767 | n/a | "kern": LOG_KERN, |
---|
768 | n/a | "lpr": LOG_LPR, |
---|
769 | n/a | "mail": LOG_MAIL, |
---|
770 | n/a | "news": LOG_NEWS, |
---|
771 | n/a | "security": LOG_AUTH, # DEPRECATED |
---|
772 | n/a | "syslog": LOG_SYSLOG, |
---|
773 | n/a | "user": LOG_USER, |
---|
774 | n/a | "uucp": LOG_UUCP, |
---|
775 | n/a | "local0": LOG_LOCAL0, |
---|
776 | n/a | "local1": LOG_LOCAL1, |
---|
777 | n/a | "local2": LOG_LOCAL2, |
---|
778 | n/a | "local3": LOG_LOCAL3, |
---|
779 | n/a | "local4": LOG_LOCAL4, |
---|
780 | n/a | "local5": LOG_LOCAL5, |
---|
781 | n/a | "local6": LOG_LOCAL6, |
---|
782 | n/a | "local7": LOG_LOCAL7, |
---|
783 | n/a | } |
---|
784 | n/a | |
---|
785 | n/a | #The map below appears to be trivially lowercasing the key. However, |
---|
786 | n/a | #there's more to it than meets the eye - in some locales, lowercasing |
---|
787 | n/a | #gives unexpected results. See SF #1524081: in the Turkish locale, |
---|
788 | n/a | #"INFO".lower() != "info" |
---|
789 | n/a | priority_map = { |
---|
790 | n/a | "DEBUG" : "debug", |
---|
791 | n/a | "INFO" : "info", |
---|
792 | n/a | "WARNING" : "warning", |
---|
793 | n/a | "ERROR" : "error", |
---|
794 | n/a | "CRITICAL" : "critical" |
---|
795 | n/a | } |
---|
796 | n/a | |
---|
797 | n/a | def __init__(self, address=('localhost', SYSLOG_UDP_PORT), |
---|
798 | n/a | facility=LOG_USER, socktype=None): |
---|
799 | n/a | """ |
---|
800 | n/a | Initialize a handler. |
---|
801 | n/a | |
---|
802 | n/a | If address is specified as a string, a UNIX socket is used. To log to a |
---|
803 | n/a | local syslogd, "SysLogHandler(address="/dev/log")" can be used. |
---|
804 | n/a | If facility is not specified, LOG_USER is used. If socktype is |
---|
805 | n/a | specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific |
---|
806 | n/a | socket type will be used. For Unix sockets, you can also specify a |
---|
807 | n/a | socktype of None, in which case socket.SOCK_DGRAM will be used, falling |
---|
808 | n/a | back to socket.SOCK_STREAM. |
---|
809 | n/a | """ |
---|
810 | n/a | logging.Handler.__init__(self) |
---|
811 | n/a | |
---|
812 | n/a | self.address = address |
---|
813 | n/a | self.facility = facility |
---|
814 | n/a | self.socktype = socktype |
---|
815 | n/a | |
---|
816 | n/a | if isinstance(address, str): |
---|
817 | n/a | self.unixsocket = True |
---|
818 | n/a | self._connect_unixsocket(address) |
---|
819 | n/a | else: |
---|
820 | n/a | self.unixsocket = False |
---|
821 | n/a | if socktype is None: |
---|
822 | n/a | socktype = socket.SOCK_DGRAM |
---|
823 | n/a | self.socket = socket.socket(socket.AF_INET, socktype) |
---|
824 | n/a | if socktype == socket.SOCK_STREAM: |
---|
825 | n/a | self.socket.connect(address) |
---|
826 | n/a | self.socktype = socktype |
---|
827 | n/a | self.formatter = None |
---|
828 | n/a | |
---|
829 | n/a | def _connect_unixsocket(self, address): |
---|
830 | n/a | use_socktype = self.socktype |
---|
831 | n/a | if use_socktype is None: |
---|
832 | n/a | use_socktype = socket.SOCK_DGRAM |
---|
833 | n/a | self.socket = socket.socket(socket.AF_UNIX, use_socktype) |
---|
834 | n/a | try: |
---|
835 | n/a | self.socket.connect(address) |
---|
836 | n/a | # it worked, so set self.socktype to the used type |
---|
837 | n/a | self.socktype = use_socktype |
---|
838 | n/a | except OSError: |
---|
839 | n/a | self.socket.close() |
---|
840 | n/a | if self.socktype is not None: |
---|
841 | n/a | # user didn't specify falling back, so fail |
---|
842 | n/a | raise |
---|
843 | n/a | use_socktype = socket.SOCK_STREAM |
---|
844 | n/a | self.socket = socket.socket(socket.AF_UNIX, use_socktype) |
---|
845 | n/a | try: |
---|
846 | n/a | self.socket.connect(address) |
---|
847 | n/a | # it worked, so set self.socktype to the used type |
---|
848 | n/a | self.socktype = use_socktype |
---|
849 | n/a | except OSError: |
---|
850 | n/a | self.socket.close() |
---|
851 | n/a | raise |
---|
852 | n/a | |
---|
853 | n/a | def encodePriority(self, facility, priority): |
---|
854 | n/a | """ |
---|
855 | n/a | Encode the facility and priority. You can pass in strings or |
---|
856 | n/a | integers - if strings are passed, the facility_names and |
---|
857 | n/a | priority_names mapping dictionaries are used to convert them to |
---|
858 | n/a | integers. |
---|
859 | n/a | """ |
---|
860 | n/a | if isinstance(facility, str): |
---|
861 | n/a | facility = self.facility_names[facility] |
---|
862 | n/a | if isinstance(priority, str): |
---|
863 | n/a | priority = self.priority_names[priority] |
---|
864 | n/a | return (facility << 3) | priority |
---|
865 | n/a | |
---|
866 | n/a | def close (self): |
---|
867 | n/a | """ |
---|
868 | n/a | Closes the socket. |
---|
869 | n/a | """ |
---|
870 | n/a | self.acquire() |
---|
871 | n/a | try: |
---|
872 | n/a | self.socket.close() |
---|
873 | n/a | logging.Handler.close(self) |
---|
874 | n/a | finally: |
---|
875 | n/a | self.release() |
---|
876 | n/a | |
---|
877 | n/a | def mapPriority(self, levelName): |
---|
878 | n/a | """ |
---|
879 | n/a | Map a logging level name to a key in the priority_names map. |
---|
880 | n/a | This is useful in two scenarios: when custom levels are being |
---|
881 | n/a | used, and in the case where you can't do a straightforward |
---|
882 | n/a | mapping by lowercasing the logging level name because of locale- |
---|
883 | n/a | specific issues (see SF #1524081). |
---|
884 | n/a | """ |
---|
885 | n/a | return self.priority_map.get(levelName, "warning") |
---|
886 | n/a | |
---|
887 | n/a | ident = '' # prepended to all messages |
---|
888 | n/a | append_nul = True # some old syslog daemons expect a NUL terminator |
---|
889 | n/a | |
---|
890 | n/a | def emit(self, record): |
---|
891 | n/a | """ |
---|
892 | n/a | Emit a record. |
---|
893 | n/a | |
---|
894 | n/a | The record is formatted, and then sent to the syslog server. If |
---|
895 | n/a | exception information is present, it is NOT sent to the server. |
---|
896 | n/a | """ |
---|
897 | n/a | try: |
---|
898 | n/a | msg = self.format(record) |
---|
899 | n/a | if self.ident: |
---|
900 | n/a | msg = self.ident + msg |
---|
901 | n/a | if self.append_nul: |
---|
902 | n/a | msg += '\000' |
---|
903 | n/a | |
---|
904 | n/a | # We need to convert record level to lowercase, maybe this will |
---|
905 | n/a | # change in the future. |
---|
906 | n/a | prio = '<%d>' % self.encodePriority(self.facility, |
---|
907 | n/a | self.mapPriority(record.levelname)) |
---|
908 | n/a | prio = prio.encode('utf-8') |
---|
909 | n/a | # Message is a string. Convert to bytes as required by RFC 5424 |
---|
910 | n/a | msg = msg.encode('utf-8') |
---|
911 | n/a | msg = prio + msg |
---|
912 | n/a | if self.unixsocket: |
---|
913 | n/a | try: |
---|
914 | n/a | self.socket.send(msg) |
---|
915 | n/a | except OSError: |
---|
916 | n/a | self.socket.close() |
---|
917 | n/a | self._connect_unixsocket(self.address) |
---|
918 | n/a | self.socket.send(msg) |
---|
919 | n/a | elif self.socktype == socket.SOCK_DGRAM: |
---|
920 | n/a | self.socket.sendto(msg, self.address) |
---|
921 | n/a | else: |
---|
922 | n/a | self.socket.sendall(msg) |
---|
923 | n/a | except Exception: |
---|
924 | n/a | self.handleError(record) |
---|
925 | n/a | |
---|
926 | n/a | class SMTPHandler(logging.Handler): |
---|
927 | n/a | """ |
---|
928 | n/a | A handler class which sends an SMTP email for each logging event. |
---|
929 | n/a | """ |
---|
930 | n/a | def __init__(self, mailhost, fromaddr, toaddrs, subject, |
---|
931 | n/a | credentials=None, secure=None, timeout=5.0): |
---|
932 | n/a | """ |
---|
933 | n/a | Initialize the handler. |
---|
934 | n/a | |
---|
935 | n/a | Initialize the instance with the from and to addresses and subject |
---|
936 | n/a | line of the email. To specify a non-standard SMTP port, use the |
---|
937 | n/a | (host, port) tuple format for the mailhost argument. To specify |
---|
938 | n/a | authentication credentials, supply a (username, password) tuple |
---|
939 | n/a | for the credentials argument. To specify the use of a secure |
---|
940 | n/a | protocol (TLS), pass in a tuple for the secure argument. This will |
---|
941 | n/a | only be used when authentication credentials are supplied. The tuple |
---|
942 | n/a | will be either an empty tuple, or a single-value tuple with the name |
---|
943 | n/a | of a keyfile, or a 2-value tuple with the names of the keyfile and |
---|
944 | n/a | certificate file. (This tuple is passed to the `starttls` method). |
---|
945 | n/a | A timeout in seconds can be specified for the SMTP connection (the |
---|
946 | n/a | default is one second). |
---|
947 | n/a | """ |
---|
948 | n/a | logging.Handler.__init__(self) |
---|
949 | n/a | if isinstance(mailhost, (list, tuple)): |
---|
950 | n/a | self.mailhost, self.mailport = mailhost |
---|
951 | n/a | else: |
---|
952 | n/a | self.mailhost, self.mailport = mailhost, None |
---|
953 | n/a | if isinstance(credentials, (list, tuple)): |
---|
954 | n/a | self.username, self.password = credentials |
---|
955 | n/a | else: |
---|
956 | n/a | self.username = None |
---|
957 | n/a | self.fromaddr = fromaddr |
---|
958 | n/a | if isinstance(toaddrs, str): |
---|
959 | n/a | toaddrs = [toaddrs] |
---|
960 | n/a | self.toaddrs = toaddrs |
---|
961 | n/a | self.subject = subject |
---|
962 | n/a | self.secure = secure |
---|
963 | n/a | self.timeout = timeout |
---|
964 | n/a | |
---|
965 | n/a | def getSubject(self, record): |
---|
966 | n/a | """ |
---|
967 | n/a | Determine the subject for the email. |
---|
968 | n/a | |
---|
969 | n/a | If you want to specify a subject line which is record-dependent, |
---|
970 | n/a | override this method. |
---|
971 | n/a | """ |
---|
972 | n/a | return self.subject |
---|
973 | n/a | |
---|
974 | n/a | def emit(self, record): |
---|
975 | n/a | """ |
---|
976 | n/a | Emit a record. |
---|
977 | n/a | |
---|
978 | n/a | Format the record and send it to the specified addressees. |
---|
979 | n/a | """ |
---|
980 | n/a | try: |
---|
981 | n/a | import smtplib |
---|
982 | n/a | from email.message import EmailMessage |
---|
983 | n/a | import email.utils |
---|
984 | n/a | |
---|
985 | n/a | port = self.mailport |
---|
986 | n/a | if not port: |
---|
987 | n/a | port = smtplib.SMTP_PORT |
---|
988 | n/a | smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) |
---|
989 | n/a | msg = EmailMessage() |
---|
990 | n/a | msg['From'] = self.fromaddr |
---|
991 | n/a | msg['To'] = ','.join(self.toaddrs) |
---|
992 | n/a | msg['Subject'] = self.getSubject(record) |
---|
993 | n/a | msg['Date'] = email.utils.localtime() |
---|
994 | n/a | msg.set_content(self.format(record)) |
---|
995 | n/a | if self.username: |
---|
996 | n/a | if self.secure is not None: |
---|
997 | n/a | smtp.ehlo() |
---|
998 | n/a | smtp.starttls(*self.secure) |
---|
999 | n/a | smtp.ehlo() |
---|
1000 | n/a | smtp.login(self.username, self.password) |
---|
1001 | n/a | smtp.send_message(msg) |
---|
1002 | n/a | smtp.quit() |
---|
1003 | n/a | except Exception: |
---|
1004 | n/a | self.handleError(record) |
---|
1005 | n/a | |
---|
1006 | n/a | class NTEventLogHandler(logging.Handler): |
---|
1007 | n/a | """ |
---|
1008 | n/a | A handler class which sends events to the NT Event Log. Adds a |
---|
1009 | n/a | registry entry for the specified application name. If no dllname is |
---|
1010 | n/a | provided, win32service.pyd (which contains some basic message |
---|
1011 | n/a | placeholders) is used. Note that use of these placeholders will make |
---|
1012 | n/a | your event logs big, as the entire message source is held in the log. |
---|
1013 | n/a | If you want slimmer logs, you have to pass in the name of your own DLL |
---|
1014 | n/a | which contains the message definitions you want to use in the event log. |
---|
1015 | n/a | """ |
---|
1016 | n/a | def __init__(self, appname, dllname=None, logtype="Application"): |
---|
1017 | n/a | logging.Handler.__init__(self) |
---|
1018 | n/a | try: |
---|
1019 | n/a | import win32evtlogutil, win32evtlog |
---|
1020 | n/a | self.appname = appname |
---|
1021 | n/a | self._welu = win32evtlogutil |
---|
1022 | n/a | if not dllname: |
---|
1023 | n/a | dllname = os.path.split(self._welu.__file__) |
---|
1024 | n/a | dllname = os.path.split(dllname[0]) |
---|
1025 | n/a | dllname = os.path.join(dllname[0], r'win32service.pyd') |
---|
1026 | n/a | self.dllname = dllname |
---|
1027 | n/a | self.logtype = logtype |
---|
1028 | n/a | self._welu.AddSourceToRegistry(appname, dllname, logtype) |
---|
1029 | n/a | self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE |
---|
1030 | n/a | self.typemap = { |
---|
1031 | n/a | logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, |
---|
1032 | n/a | logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, |
---|
1033 | n/a | logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, |
---|
1034 | n/a | logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, |
---|
1035 | n/a | logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, |
---|
1036 | n/a | } |
---|
1037 | n/a | except ImportError: |
---|
1038 | n/a | print("The Python Win32 extensions for NT (service, event "\ |
---|
1039 | n/a | "logging) appear not to be available.") |
---|
1040 | n/a | self._welu = None |
---|
1041 | n/a | |
---|
1042 | n/a | def getMessageID(self, record): |
---|
1043 | n/a | """ |
---|
1044 | n/a | Return the message ID for the event record. If you are using your |
---|
1045 | n/a | own messages, you could do this by having the msg passed to the |
---|
1046 | n/a | logger being an ID rather than a formatting string. Then, in here, |
---|
1047 | n/a | you could use a dictionary lookup to get the message ID. This |
---|
1048 | n/a | version returns 1, which is the base message ID in win32service.pyd. |
---|
1049 | n/a | """ |
---|
1050 | n/a | return 1 |
---|
1051 | n/a | |
---|
1052 | n/a | def getEventCategory(self, record): |
---|
1053 | n/a | """ |
---|
1054 | n/a | Return the event category for the record. |
---|
1055 | n/a | |
---|
1056 | n/a | Override this if you want to specify your own categories. This version |
---|
1057 | n/a | returns 0. |
---|
1058 | n/a | """ |
---|
1059 | n/a | return 0 |
---|
1060 | n/a | |
---|
1061 | n/a | def getEventType(self, record): |
---|
1062 | n/a | """ |
---|
1063 | n/a | Return the event type for the record. |
---|
1064 | n/a | |
---|
1065 | n/a | Override this if you want to specify your own types. This version does |
---|
1066 | n/a | a mapping using the handler's typemap attribute, which is set up in |
---|
1067 | n/a | __init__() to a dictionary which contains mappings for DEBUG, INFO, |
---|
1068 | n/a | WARNING, ERROR and CRITICAL. If you are using your own levels you will |
---|
1069 | n/a | either need to override this method or place a suitable dictionary in |
---|
1070 | n/a | the handler's typemap attribute. |
---|
1071 | n/a | """ |
---|
1072 | n/a | return self.typemap.get(record.levelno, self.deftype) |
---|
1073 | n/a | |
---|
1074 | n/a | def emit(self, record): |
---|
1075 | n/a | """ |
---|
1076 | n/a | Emit a record. |
---|
1077 | n/a | |
---|
1078 | n/a | Determine the message ID, event category and event type. Then |
---|
1079 | n/a | log the message in the NT event log. |
---|
1080 | n/a | """ |
---|
1081 | n/a | if self._welu: |
---|
1082 | n/a | try: |
---|
1083 | n/a | id = self.getMessageID(record) |
---|
1084 | n/a | cat = self.getEventCategory(record) |
---|
1085 | n/a | type = self.getEventType(record) |
---|
1086 | n/a | msg = self.format(record) |
---|
1087 | n/a | self._welu.ReportEvent(self.appname, id, cat, type, [msg]) |
---|
1088 | n/a | except Exception: |
---|
1089 | n/a | self.handleError(record) |
---|
1090 | n/a | |
---|
1091 | n/a | def close(self): |
---|
1092 | n/a | """ |
---|
1093 | n/a | Clean up this handler. |
---|
1094 | n/a | |
---|
1095 | n/a | You can remove the application name from the registry as a |
---|
1096 | n/a | source of event log entries. However, if you do this, you will |
---|
1097 | n/a | not be able to see the events as you intended in the Event Log |
---|
1098 | n/a | Viewer - it needs to be able to access the registry to get the |
---|
1099 | n/a | DLL name. |
---|
1100 | n/a | """ |
---|
1101 | n/a | #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) |
---|
1102 | n/a | logging.Handler.close(self) |
---|
1103 | n/a | |
---|
1104 | n/a | class HTTPHandler(logging.Handler): |
---|
1105 | n/a | """ |
---|
1106 | n/a | A class which sends records to a Web server, using either GET or |
---|
1107 | n/a | POST semantics. |
---|
1108 | n/a | """ |
---|
1109 | n/a | def __init__(self, host, url, method="GET", secure=False, credentials=None, |
---|
1110 | n/a | context=None): |
---|
1111 | n/a | """ |
---|
1112 | n/a | Initialize the instance with the host, the request URL, and the method |
---|
1113 | n/a | ("GET" or "POST") |
---|
1114 | n/a | """ |
---|
1115 | n/a | logging.Handler.__init__(self) |
---|
1116 | n/a | method = method.upper() |
---|
1117 | n/a | if method not in ["GET", "POST"]: |
---|
1118 | n/a | raise ValueError("method must be GET or POST") |
---|
1119 | n/a | if not secure and context is not None: |
---|
1120 | n/a | raise ValueError("context parameter only makes sense " |
---|
1121 | n/a | "with secure=True") |
---|
1122 | n/a | self.host = host |
---|
1123 | n/a | self.url = url |
---|
1124 | n/a | self.method = method |
---|
1125 | n/a | self.secure = secure |
---|
1126 | n/a | self.credentials = credentials |
---|
1127 | n/a | self.context = context |
---|
1128 | n/a | |
---|
1129 | n/a | def mapLogRecord(self, record): |
---|
1130 | n/a | """ |
---|
1131 | n/a | Default implementation of mapping the log record into a dict |
---|
1132 | n/a | that is sent as the CGI data. Overwrite in your class. |
---|
1133 | n/a | Contributed by Franz Glasner. |
---|
1134 | n/a | """ |
---|
1135 | n/a | return record.__dict__ |
---|
1136 | n/a | |
---|
1137 | n/a | def emit(self, record): |
---|
1138 | n/a | """ |
---|
1139 | n/a | Emit a record. |
---|
1140 | n/a | |
---|
1141 | n/a | Send the record to the Web server as a percent-encoded dictionary |
---|
1142 | n/a | """ |
---|
1143 | n/a | try: |
---|
1144 | n/a | import http.client, urllib.parse |
---|
1145 | n/a | host = self.host |
---|
1146 | n/a | if self.secure: |
---|
1147 | n/a | h = http.client.HTTPSConnection(host, context=self.context) |
---|
1148 | n/a | else: |
---|
1149 | n/a | h = http.client.HTTPConnection(host) |
---|
1150 | n/a | url = self.url |
---|
1151 | n/a | data = urllib.parse.urlencode(self.mapLogRecord(record)) |
---|
1152 | n/a | if self.method == "GET": |
---|
1153 | n/a | if (url.find('?') >= 0): |
---|
1154 | n/a | sep = '&' |
---|
1155 | n/a | else: |
---|
1156 | n/a | sep = '?' |
---|
1157 | n/a | url = url + "%c%s" % (sep, data) |
---|
1158 | n/a | h.putrequest(self.method, url) |
---|
1159 | n/a | # support multiple hosts on one IP address... |
---|
1160 | n/a | # need to strip optional :port from host, if present |
---|
1161 | n/a | i = host.find(":") |
---|
1162 | n/a | if i >= 0: |
---|
1163 | n/a | host = host[:i] |
---|
1164 | n/a | h.putheader("Host", host) |
---|
1165 | n/a | if self.method == "POST": |
---|
1166 | n/a | h.putheader("Content-type", |
---|
1167 | n/a | "application/x-www-form-urlencoded") |
---|
1168 | n/a | h.putheader("Content-length", str(len(data))) |
---|
1169 | n/a | if self.credentials: |
---|
1170 | n/a | import base64 |
---|
1171 | n/a | s = ('%s:%s' % self.credentials).encode('utf-8') |
---|
1172 | n/a | s = 'Basic ' + base64.b64encode(s).strip().decode('ascii') |
---|
1173 | n/a | h.putheader('Authorization', s) |
---|
1174 | n/a | h.endheaders() |
---|
1175 | n/a | if self.method == "POST": |
---|
1176 | n/a | h.send(data.encode('utf-8')) |
---|
1177 | n/a | h.getresponse() #can't do anything with the result |
---|
1178 | n/a | except Exception: |
---|
1179 | n/a | self.handleError(record) |
---|
1180 | n/a | |
---|
1181 | n/a | class BufferingHandler(logging.Handler): |
---|
1182 | n/a | """ |
---|
1183 | n/a | A handler class which buffers logging records in memory. Whenever each |
---|
1184 | n/a | record is added to the buffer, a check is made to see if the buffer should |
---|
1185 | n/a | be flushed. If it should, then flush() is expected to do what's needed. |
---|
1186 | n/a | """ |
---|
1187 | n/a | def __init__(self, capacity): |
---|
1188 | n/a | """ |
---|
1189 | n/a | Initialize the handler with the buffer size. |
---|
1190 | n/a | """ |
---|
1191 | n/a | logging.Handler.__init__(self) |
---|
1192 | n/a | self.capacity = capacity |
---|
1193 | n/a | self.buffer = [] |
---|
1194 | n/a | |
---|
1195 | n/a | def shouldFlush(self, record): |
---|
1196 | n/a | """ |
---|
1197 | n/a | Should the handler flush its buffer? |
---|
1198 | n/a | |
---|
1199 | n/a | Returns true if the buffer is up to capacity. This method can be |
---|
1200 | n/a | overridden to implement custom flushing strategies. |
---|
1201 | n/a | """ |
---|
1202 | n/a | return (len(self.buffer) >= self.capacity) |
---|
1203 | n/a | |
---|
1204 | n/a | def emit(self, record): |
---|
1205 | n/a | """ |
---|
1206 | n/a | Emit a record. |
---|
1207 | n/a | |
---|
1208 | n/a | Append the record. If shouldFlush() tells us to, call flush() to process |
---|
1209 | n/a | the buffer. |
---|
1210 | n/a | """ |
---|
1211 | n/a | self.buffer.append(record) |
---|
1212 | n/a | if self.shouldFlush(record): |
---|
1213 | n/a | self.flush() |
---|
1214 | n/a | |
---|
1215 | n/a | def flush(self): |
---|
1216 | n/a | """ |
---|
1217 | n/a | Override to implement custom flushing behaviour. |
---|
1218 | n/a | |
---|
1219 | n/a | This version just zaps the buffer to empty. |
---|
1220 | n/a | """ |
---|
1221 | n/a | self.acquire() |
---|
1222 | n/a | try: |
---|
1223 | n/a | self.buffer = [] |
---|
1224 | n/a | finally: |
---|
1225 | n/a | self.release() |
---|
1226 | n/a | |
---|
1227 | n/a | def close(self): |
---|
1228 | n/a | """ |
---|
1229 | n/a | Close the handler. |
---|
1230 | n/a | |
---|
1231 | n/a | This version just flushes and chains to the parent class' close(). |
---|
1232 | n/a | """ |
---|
1233 | n/a | try: |
---|
1234 | n/a | self.flush() |
---|
1235 | n/a | finally: |
---|
1236 | n/a | logging.Handler.close(self) |
---|
1237 | n/a | |
---|
1238 | n/a | class MemoryHandler(BufferingHandler): |
---|
1239 | n/a | """ |
---|
1240 | n/a | A handler class which buffers logging records in memory, periodically |
---|
1241 | n/a | flushing them to a target handler. Flushing occurs whenever the buffer |
---|
1242 | n/a | is full, or when an event of a certain severity or greater is seen. |
---|
1243 | n/a | """ |
---|
1244 | n/a | def __init__(self, capacity, flushLevel=logging.ERROR, target=None, |
---|
1245 | n/a | flushOnClose=True): |
---|
1246 | n/a | """ |
---|
1247 | n/a | Initialize the handler with the buffer size, the level at which |
---|
1248 | n/a | flushing should occur and an optional target. |
---|
1249 | n/a | |
---|
1250 | n/a | Note that without a target being set either here or via setTarget(), |
---|
1251 | n/a | a MemoryHandler is no use to anyone! |
---|
1252 | n/a | |
---|
1253 | n/a | The ``flushOnClose`` argument is ``True`` for backward compatibility |
---|
1254 | n/a | reasons - the old behaviour is that when the handler is closed, the |
---|
1255 | n/a | buffer is flushed, even if the flush level hasn't been exceeded nor the |
---|
1256 | n/a | capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. |
---|
1257 | n/a | """ |
---|
1258 | n/a | BufferingHandler.__init__(self, capacity) |
---|
1259 | n/a | self.flushLevel = flushLevel |
---|
1260 | n/a | self.target = target |
---|
1261 | n/a | # See Issue #26559 for why this has been added |
---|
1262 | n/a | self.flushOnClose = flushOnClose |
---|
1263 | n/a | |
---|
1264 | n/a | def shouldFlush(self, record): |
---|
1265 | n/a | """ |
---|
1266 | n/a | Check for buffer full or a record at the flushLevel or higher. |
---|
1267 | n/a | """ |
---|
1268 | n/a | return (len(self.buffer) >= self.capacity) or \ |
---|
1269 | n/a | (record.levelno >= self.flushLevel) |
---|
1270 | n/a | |
---|
1271 | n/a | def setTarget(self, target): |
---|
1272 | n/a | """ |
---|
1273 | n/a | Set the target handler for this handler. |
---|
1274 | n/a | """ |
---|
1275 | n/a | self.target = target |
---|
1276 | n/a | |
---|
1277 | n/a | def flush(self): |
---|
1278 | n/a | """ |
---|
1279 | n/a | For a MemoryHandler, flushing means just sending the buffered |
---|
1280 | n/a | records to the target, if there is one. Override if you want |
---|
1281 | n/a | different behaviour. |
---|
1282 | n/a | |
---|
1283 | n/a | The record buffer is also cleared by this operation. |
---|
1284 | n/a | """ |
---|
1285 | n/a | self.acquire() |
---|
1286 | n/a | try: |
---|
1287 | n/a | if self.target: |
---|
1288 | n/a | for record in self.buffer: |
---|
1289 | n/a | self.target.handle(record) |
---|
1290 | n/a | self.buffer = [] |
---|
1291 | n/a | finally: |
---|
1292 | n/a | self.release() |
---|
1293 | n/a | |
---|
1294 | n/a | def close(self): |
---|
1295 | n/a | """ |
---|
1296 | n/a | Flush, if appropriately configured, set the target to None and lose the |
---|
1297 | n/a | buffer. |
---|
1298 | n/a | """ |
---|
1299 | n/a | try: |
---|
1300 | n/a | if self.flushOnClose: |
---|
1301 | n/a | self.flush() |
---|
1302 | n/a | finally: |
---|
1303 | n/a | self.acquire() |
---|
1304 | n/a | try: |
---|
1305 | n/a | self.target = None |
---|
1306 | n/a | BufferingHandler.close(self) |
---|
1307 | n/a | finally: |
---|
1308 | n/a | self.release() |
---|
1309 | n/a | |
---|
1310 | n/a | |
---|
1311 | n/a | class QueueHandler(logging.Handler): |
---|
1312 | n/a | """ |
---|
1313 | n/a | This handler sends events to a queue. Typically, it would be used together |
---|
1314 | n/a | with a multiprocessing Queue to centralise logging to file in one process |
---|
1315 | n/a | (in a multi-process application), so as to avoid file write contention |
---|
1316 | n/a | between processes. |
---|
1317 | n/a | |
---|
1318 | n/a | This code is new in Python 3.2, but this class can be copy pasted into |
---|
1319 | n/a | user code for use with earlier Python versions. |
---|
1320 | n/a | """ |
---|
1321 | n/a | |
---|
1322 | n/a | def __init__(self, queue): |
---|
1323 | n/a | """ |
---|
1324 | n/a | Initialise an instance, using the passed queue. |
---|
1325 | n/a | """ |
---|
1326 | n/a | logging.Handler.__init__(self) |
---|
1327 | n/a | self.queue = queue |
---|
1328 | n/a | |
---|
1329 | n/a | def enqueue(self, record): |
---|
1330 | n/a | """ |
---|
1331 | n/a | Enqueue a record. |
---|
1332 | n/a | |
---|
1333 | n/a | The base implementation uses put_nowait. You may want to override |
---|
1334 | n/a | this method if you want to use blocking, timeouts or custom queue |
---|
1335 | n/a | implementations. |
---|
1336 | n/a | """ |
---|
1337 | n/a | self.queue.put_nowait(record) |
---|
1338 | n/a | |
---|
1339 | n/a | def prepare(self, record): |
---|
1340 | n/a | """ |
---|
1341 | n/a | Prepares a record for queuing. The object returned by this method is |
---|
1342 | n/a | enqueued. |
---|
1343 | n/a | |
---|
1344 | n/a | The base implementation formats the record to merge the message |
---|
1345 | n/a | and arguments, and removes unpickleable items from the record |
---|
1346 | n/a | in-place. |
---|
1347 | n/a | |
---|
1348 | n/a | You might want to override this method if you want to convert |
---|
1349 | n/a | the record to a dict or JSON string, or send a modified copy |
---|
1350 | n/a | of the record while leaving the original intact. |
---|
1351 | n/a | """ |
---|
1352 | n/a | # The format operation gets traceback text into record.exc_text |
---|
1353 | n/a | # (if there's exception data), and also puts the message into |
---|
1354 | n/a | # record.message. We can then use this to replace the original |
---|
1355 | n/a | # msg + args, as these might be unpickleable. We also zap the |
---|
1356 | n/a | # exc_info attribute, as it's no longer needed and, if not None, |
---|
1357 | n/a | # will typically not be pickleable. |
---|
1358 | n/a | self.format(record) |
---|
1359 | n/a | record.msg = record.message |
---|
1360 | n/a | record.args = None |
---|
1361 | n/a | record.exc_info = None |
---|
1362 | n/a | return record |
---|
1363 | n/a | |
---|
1364 | n/a | def emit(self, record): |
---|
1365 | n/a | """ |
---|
1366 | n/a | Emit a record. |
---|
1367 | n/a | |
---|
1368 | n/a | Writes the LogRecord to the queue, preparing it for pickling first. |
---|
1369 | n/a | """ |
---|
1370 | n/a | try: |
---|
1371 | n/a | self.enqueue(self.prepare(record)) |
---|
1372 | n/a | except Exception: |
---|
1373 | n/a | self.handleError(record) |
---|
1374 | n/a | |
---|
1375 | n/a | if threading: |
---|
1376 | n/a | class QueueListener(object): |
---|
1377 | n/a | """ |
---|
1378 | n/a | This class implements an internal threaded listener which watches for |
---|
1379 | n/a | LogRecords being added to a queue, removes them and passes them to a |
---|
1380 | n/a | list of handlers for processing. |
---|
1381 | n/a | """ |
---|
1382 | n/a | _sentinel = None |
---|
1383 | n/a | |
---|
1384 | n/a | def __init__(self, queue, *handlers, respect_handler_level=False): |
---|
1385 | n/a | """ |
---|
1386 | n/a | Initialise an instance with the specified queue and |
---|
1387 | n/a | handlers. |
---|
1388 | n/a | """ |
---|
1389 | n/a | self.queue = queue |
---|
1390 | n/a | self.handlers = handlers |
---|
1391 | n/a | self._thread = None |
---|
1392 | n/a | self.respect_handler_level = respect_handler_level |
---|
1393 | n/a | |
---|
1394 | n/a | def dequeue(self, block): |
---|
1395 | n/a | """ |
---|
1396 | n/a | Dequeue a record and return it, optionally blocking. |
---|
1397 | n/a | |
---|
1398 | n/a | The base implementation uses get. You may want to override this method |
---|
1399 | n/a | if you want to use timeouts or work with custom queue implementations. |
---|
1400 | n/a | """ |
---|
1401 | n/a | return self.queue.get(block) |
---|
1402 | n/a | |
---|
1403 | n/a | def start(self): |
---|
1404 | n/a | """ |
---|
1405 | n/a | Start the listener. |
---|
1406 | n/a | |
---|
1407 | n/a | This starts up a background thread to monitor the queue for |
---|
1408 | n/a | LogRecords to process. |
---|
1409 | n/a | """ |
---|
1410 | n/a | self._thread = t = threading.Thread(target=self._monitor) |
---|
1411 | n/a | t.daemon = True |
---|
1412 | n/a | t.start() |
---|
1413 | n/a | |
---|
1414 | n/a | def prepare(self , record): |
---|
1415 | n/a | """ |
---|
1416 | n/a | Prepare a record for handling. |
---|
1417 | n/a | |
---|
1418 | n/a | This method just returns the passed-in record. You may want to |
---|
1419 | n/a | override this method if you need to do any custom marshalling or |
---|
1420 | n/a | manipulation of the record before passing it to the handlers. |
---|
1421 | n/a | """ |
---|
1422 | n/a | return record |
---|
1423 | n/a | |
---|
1424 | n/a | def handle(self, record): |
---|
1425 | n/a | """ |
---|
1426 | n/a | Handle a record. |
---|
1427 | n/a | |
---|
1428 | n/a | This just loops through the handlers offering them the record |
---|
1429 | n/a | to handle. |
---|
1430 | n/a | """ |
---|
1431 | n/a | record = self.prepare(record) |
---|
1432 | n/a | for handler in self.handlers: |
---|
1433 | n/a | if not self.respect_handler_level: |
---|
1434 | n/a | process = True |
---|
1435 | n/a | else: |
---|
1436 | n/a | process = record.levelno >= handler.level |
---|
1437 | n/a | if process: |
---|
1438 | n/a | handler.handle(record) |
---|
1439 | n/a | |
---|
1440 | n/a | def _monitor(self): |
---|
1441 | n/a | """ |
---|
1442 | n/a | Monitor the queue for records, and ask the handler |
---|
1443 | n/a | to deal with them. |
---|
1444 | n/a | |
---|
1445 | n/a | This method runs on a separate, internal thread. |
---|
1446 | n/a | The thread will terminate if it sees a sentinel object in the queue. |
---|
1447 | n/a | """ |
---|
1448 | n/a | q = self.queue |
---|
1449 | n/a | has_task_done = hasattr(q, 'task_done') |
---|
1450 | n/a | while True: |
---|
1451 | n/a | try: |
---|
1452 | n/a | record = self.dequeue(True) |
---|
1453 | n/a | if record is self._sentinel: |
---|
1454 | n/a | break |
---|
1455 | n/a | self.handle(record) |
---|
1456 | n/a | if has_task_done: |
---|
1457 | n/a | q.task_done() |
---|
1458 | n/a | except queue.Empty: |
---|
1459 | n/a | break |
---|
1460 | n/a | |
---|
1461 | n/a | def enqueue_sentinel(self): |
---|
1462 | n/a | """ |
---|
1463 | n/a | This is used to enqueue the sentinel record. |
---|
1464 | n/a | |
---|
1465 | n/a | The base implementation uses put_nowait. You may want to override this |
---|
1466 | n/a | method if you want to use timeouts or work with custom queue |
---|
1467 | n/a | implementations. |
---|
1468 | n/a | """ |
---|
1469 | n/a | self.queue.put_nowait(self._sentinel) |
---|
1470 | n/a | |
---|
1471 | n/a | def stop(self): |
---|
1472 | n/a | """ |
---|
1473 | n/a | Stop the listener. |
---|
1474 | n/a | |
---|
1475 | n/a | This asks the thread to terminate, and then waits for it to do so. |
---|
1476 | n/a | Note that if you don't call this before your application exits, there |
---|
1477 | n/a | may be some records still left on the queue, which won't be processed. |
---|
1478 | n/a | """ |
---|
1479 | n/a | self.enqueue_sentinel() |
---|
1480 | n/a | self._thread.join() |
---|
1481 | n/a | self._thread = None |
---|