move sections
[python/dscho.git] / Lib / logging / __init__.py
blob80ec6724e44c3d091e6120a6eeebfa47aecc1907
1 # Copyright 2001-2010 by Vinay Sajip. All Rights Reserved.
3 # Permission to use, copy, modify, and distribute this software and its
4 # documentation for any purpose and without fee is hereby granted,
5 # provided that the above copyright notice appear in all copies and that
6 # both that copyright notice and this permission notice appear in
7 # supporting documentation, and that the name of Vinay Sajip
8 # not be used in advertising or publicity pertaining to distribution
9 # of the software without specific, written prior permission.
10 # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
11 # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
12 # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
13 # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
14 # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
15 # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 """
18 Logging package for Python. Based on PEP 282 and comments thereto in
19 comp.lang.python, and influenced by Apache's log4j system.
21 Copyright (C) 2001-2010 Vinay Sajip. All Rights Reserved.
23 To use, simply 'import logging' and log away!
24 """
26 import sys, os, time, cStringIO, traceback, warnings, weakref
28 __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
29 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
30 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
31 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
32 'captureWarnings', 'critical', 'debug', 'disable', 'error',
33 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
34 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning']
36 try:
37 import codecs
38 except ImportError:
39 codecs = None
41 try:
42 import thread
43 import threading
44 except ImportError:
45 thread = None
47 __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
48 __status__ = "production"
49 __version__ = "0.5.1.2"
50 __date__ = "07 February 2010"
52 #---------------------------------------------------------------------------
53 # Miscellaneous module data
54 #---------------------------------------------------------------------------
55 try:
56 unicode
57 _unicode = True
58 except NameError:
59 _unicode = False
62 # _srcfile is used when walking the stack to check when we've got the first
63 # caller stack frame.
65 if hasattr(sys, 'frozen'): #support for py2exe
66 _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:])
67 elif __file__[-4:].lower() in ['.pyc', '.pyo']:
68 _srcfile = __file__[:-4] + '.py'
69 else:
70 _srcfile = __file__
71 _srcfile = os.path.normcase(_srcfile)
73 # next bit filched from 1.5.2's inspect.py
74 def currentframe():
75 """Return the frame object for the caller's stack frame."""
76 try:
77 raise Exception
78 except:
79 return sys.exc_info()[2].tb_frame.f_back
81 if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)
82 # done filching
84 # _srcfile is only used in conjunction with sys._getframe().
85 # To provide compatibility with older versions of Python, set _srcfile
86 # to None if _getframe() is not available; this value will prevent
87 # findCaller() from being called.
88 #if not hasattr(sys, "_getframe"):
89 # _srcfile = None
92 #_startTime is used as the base when calculating the relative time of events
94 _startTime = time.time()
97 #raiseExceptions is used to see if exceptions during handling should be
98 #propagated
100 raiseExceptions = 1
103 # If you don't want threading information in the log, set this to zero
105 logThreads = 1
108 # If you don't want multiprocessing information in the log, set this to zero
110 logMultiprocessing = 1
113 # If you don't want process information in the log, set this to zero
115 logProcesses = 1
117 #---------------------------------------------------------------------------
118 # Level related stuff
119 #---------------------------------------------------------------------------
121 # Default levels and level names, these can be replaced with any positive set
122 # of values having corresponding names. There is a pseudo-level, NOTSET, which
123 # is only really there as a lower limit for user-defined levels. Handlers and
124 # loggers are initialized with NOTSET so that they will log all messages, even
125 # at user-defined levels.
128 CRITICAL = 50
129 FATAL = CRITICAL
130 ERROR = 40
131 WARNING = 30
132 WARN = WARNING
133 INFO = 20
134 DEBUG = 10
135 NOTSET = 0
137 _levelNames = {
138 CRITICAL : 'CRITICAL',
139 ERROR : 'ERROR',
140 WARNING : 'WARNING',
141 INFO : 'INFO',
142 DEBUG : 'DEBUG',
143 NOTSET : 'NOTSET',
144 'CRITICAL' : CRITICAL,
145 'ERROR' : ERROR,
146 'WARN' : WARNING,
147 'WARNING' : WARNING,
148 'INFO' : INFO,
149 'DEBUG' : DEBUG,
150 'NOTSET' : NOTSET,
153 def getLevelName(level):
155 Return the textual representation of logging level 'level'.
157 If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
158 INFO, DEBUG) then you get the corresponding string. If you have
159 associated levels with names using addLevelName then the name you have
160 associated with 'level' is returned.
162 If a numeric value corresponding to one of the defined levels is passed
163 in, the corresponding string representation is returned.
165 Otherwise, the string "Level %s" % level is returned.
167 return _levelNames.get(level, ("Level %s" % level))
169 def addLevelName(level, levelName):
171 Associate 'levelName' with 'level'.
173 This is used when converting levels to text during message formatting.
175 _acquireLock()
176 try: #unlikely to cause an exception, but you never know...
177 _levelNames[level] = levelName
178 _levelNames[levelName] = level
179 finally:
180 _releaseLock()
182 def _checkLevel(level):
183 if isinstance(level, int):
184 rv = level
185 elif str(level) == level:
186 if level not in _levelNames:
187 raise ValueError("Unknown level: %r" % level)
188 rv = _levelNames[level]
189 else:
190 raise TypeError("Level not an integer or a valid string: %r" % level)
191 return rv
193 #---------------------------------------------------------------------------
194 # Thread-related stuff
195 #---------------------------------------------------------------------------
198 #_lock is used to serialize access to shared data structures in this module.
199 #This needs to be an RLock because fileConfig() creates and configures
200 #Handlers, and so might arbitrary user threads. Since Handler code updates the
201 #shared dictionary _handlers, it needs to acquire the lock. But if configuring,
202 #the lock would already have been acquired - so we need an RLock.
203 #The same argument applies to Loggers and Manager.loggerDict.
205 if thread:
206 _lock = threading.RLock()
207 else:
208 _lock = None
210 def _acquireLock():
212 Acquire the module-level lock for serializing access to shared data.
214 This should be released with _releaseLock().
216 if _lock:
217 _lock.acquire()
219 def _releaseLock():
221 Release the module-level lock acquired by calling _acquireLock().
223 if _lock:
224 _lock.release()
226 #---------------------------------------------------------------------------
227 # The logging record
228 #---------------------------------------------------------------------------
230 class LogRecord(object):
232 A LogRecord instance represents an event being logged.
234 LogRecord instances are created every time something is logged. They
235 contain all the information pertinent to the event being logged. The
236 main information passed in is in msg and args, which are combined
237 using str(msg) % args to create the message field of the record. The
238 record also includes information such as when the record was created,
239 the source line where the logging call was made, and any exception
240 information to be logged.
242 def __init__(self, name, level, pathname, lineno,
243 msg, args, exc_info, func=None):
245 Initialize a logging record with interesting information.
247 ct = time.time()
248 self.name = name
249 self.msg = msg
251 # The following statement allows passing of a dictionary as a sole
252 # argument, so that you can do something like
253 # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
254 # Suggested by Stefan Behnel.
255 # Note that without the test for args[0], we get a problem because
256 # during formatting, we test to see if the arg is present using
257 # 'if self.args:'. If the event being logged is e.g. 'Value is %d'
258 # and if the passed arg fails 'if self.args:' then no formatting
259 # is done. For example, logger.warn('Value is %d', 0) would log
260 # 'Value is %d' instead of 'Value is 0'.
261 # For the use case of passing a dictionary, this should not be a
262 # problem.
263 if args and len(args) == 1 and isinstance(args[0], dict) and args[0]:
264 args = args[0]
265 self.args = args
266 self.levelname = getLevelName(level)
267 self.levelno = level
268 self.pathname = pathname
269 try:
270 self.filename = os.path.basename(pathname)
271 self.module = os.path.splitext(self.filename)[0]
272 except (TypeError, ValueError, AttributeError):
273 self.filename = pathname
274 self.module = "Unknown module"
275 self.exc_info = exc_info
276 self.exc_text = None # used to cache the traceback text
277 self.lineno = lineno
278 self.funcName = func
279 self.created = ct
280 self.msecs = (ct - long(ct)) * 1000
281 self.relativeCreated = (self.created - _startTime) * 1000
282 if logThreads and thread:
283 self.thread = thread.get_ident()
284 self.threadName = threading.current_thread().name
285 else:
286 self.thread = None
287 self.threadName = None
288 if not logMultiprocessing:
289 self.processName = None
290 else:
291 self.processName = 'MainProcess'
292 mp = sys.modules.get('multiprocessing')
293 if mp is not None:
294 # Errors may occur if multiprocessing has not finished loading
295 # yet - e.g. if a custom import hook causes third-party code
296 # to run when multiprocessing calls import. See issue 8200
297 # for an example
298 try:
299 self.processName = mp.current_process().name
300 except StandardError:
301 pass
302 if logProcesses and hasattr(os, 'getpid'):
303 self.process = os.getpid()
304 else:
305 self.process = None
307 def __str__(self):
308 return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
309 self.pathname, self.lineno, self.msg)
311 def getMessage(self):
313 Return the message for this LogRecord.
315 Return the message for this LogRecord after merging any user-supplied
316 arguments with the message.
318 if not _unicode: #if no unicode support...
319 msg = str(self.msg)
320 else:
321 msg = self.msg
322 if not isinstance(msg, basestring):
323 try:
324 msg = str(self.msg)
325 except UnicodeError:
326 msg = self.msg #Defer encoding till later
327 if self.args:
328 msg = msg % self.args
329 return msg
331 def makeLogRecord(dict):
333 Make a LogRecord whose attributes are defined by the specified dictionary,
334 This function is useful for converting a logging event received over
335 a socket connection (which is sent as a dictionary) into a LogRecord
336 instance.
338 rv = LogRecord(None, None, "", 0, "", (), None, None)
339 rv.__dict__.update(dict)
340 return rv
342 #---------------------------------------------------------------------------
343 # Formatter classes and functions
344 #---------------------------------------------------------------------------
346 class Formatter(object):
348 Formatter instances are used to convert a LogRecord to text.
350 Formatters need to know how a LogRecord is constructed. They are
351 responsible for converting a LogRecord to (usually) a string which can
352 be interpreted by either a human or an external system. The base Formatter
353 allows a formatting string to be specified. If none is supplied, the
354 default value of "%s(message)\\n" is used.
356 The Formatter can be initialized with a format string which makes use of
357 knowledge of the LogRecord attributes - e.g. the default value mentioned
358 above makes use of the fact that the user's message and arguments are pre-
359 formatted into a LogRecord's message attribute. Currently, the useful
360 attributes in a LogRecord are described by:
362 %(name)s Name of the logger (logging channel)
363 %(levelno)s Numeric logging level for the message (DEBUG, INFO,
364 WARNING, ERROR, CRITICAL)
365 %(levelname)s Text logging level for the message ("DEBUG", "INFO",
366 "WARNING", "ERROR", "CRITICAL")
367 %(pathname)s Full pathname of the source file where the logging
368 call was issued (if available)
369 %(filename)s Filename portion of pathname
370 %(module)s Module (name portion of filename)
371 %(lineno)d Source line number where the logging call was issued
372 (if available)
373 %(funcName)s Function name
374 %(created)f Time when the LogRecord was created (time.time()
375 return value)
376 %(asctime)s Textual time when the LogRecord was created
377 %(msecs)d Millisecond portion of the creation time
378 %(relativeCreated)d Time in milliseconds when the LogRecord was created,
379 relative to the time the logging module was loaded
380 (typically at application startup time)
381 %(thread)d Thread ID (if available)
382 %(threadName)s Thread name (if available)
383 %(process)d Process ID (if available)
384 %(message)s The result of record.getMessage(), computed just as
385 the record is emitted
388 converter = time.localtime
390 def __init__(self, fmt=None, datefmt=None):
392 Initialize the formatter with specified format strings.
394 Initialize the formatter either with the specified format string, or a
395 default as described above. Allow for specialized date formatting with
396 the optional datefmt argument (if omitted, you get the ISO8601 format).
398 if fmt:
399 self._fmt = fmt
400 else:
401 self._fmt = "%(message)s"
402 self.datefmt = datefmt
404 def formatTime(self, record, datefmt=None):
406 Return the creation time of the specified LogRecord as formatted text.
408 This method should be called from format() by a formatter which
409 wants to make use of a formatted time. This method can be overridden
410 in formatters to provide for any specific requirement, but the
411 basic behaviour is as follows: if datefmt (a string) is specified,
412 it is used with time.strftime() to format the creation time of the
413 record. Otherwise, the ISO8601 format is used. The resulting
414 string is returned. This function uses a user-configurable function
415 to convert the creation time to a tuple. By default, time.localtime()
416 is used; to change this for a particular formatter instance, set the
417 'converter' attribute to a function with the same signature as
418 time.localtime() or time.gmtime(). To change it for all formatters,
419 for example if you want all logging times to be shown in GMT,
420 set the 'converter' attribute in the Formatter class.
422 ct = self.converter(record.created)
423 if datefmt:
424 s = time.strftime(datefmt, ct)
425 else:
426 t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
427 s = "%s,%03d" % (t, record.msecs)
428 return s
430 def formatException(self, ei):
432 Format and return the specified exception information as a string.
434 This default implementation just uses
435 traceback.print_exception()
437 sio = cStringIO.StringIO()
438 traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
439 s = sio.getvalue()
440 sio.close()
441 if s[-1:] == "\n":
442 s = s[:-1]
443 return s
445 def usesTime(self):
447 Check if the format uses the creation time of the record.
449 return self._fmt.find("%(asctime)") >= 0
451 def format(self, record):
453 Format the specified record as text.
455 The record's attribute dictionary is used as the operand to a
456 string formatting operation which yields the returned string.
457 Before formatting the dictionary, a couple of preparatory steps
458 are carried out. The message attribute of the record is computed
459 using LogRecord.getMessage(). If the formatting string uses the
460 time (as determined by a call to usesTime(), formatTime() is
461 called to format the event time. If there is exception information,
462 it is formatted using formatException() and appended to the message.
464 record.message = record.getMessage()
465 if self.usesTime():
466 record.asctime = self.formatTime(record, self.datefmt)
467 s = self._fmt % record.__dict__
468 if record.exc_info:
469 # Cache the traceback text to avoid converting it multiple times
470 # (it's constant anyway)
471 if not record.exc_text:
472 record.exc_text = self.formatException(record.exc_info)
473 if record.exc_text:
474 if s[-1:] != "\n":
475 s = s + "\n"
476 try:
477 s = s + record.exc_text
478 except UnicodeError:
479 # Sometimes filenames have non-ASCII chars, which can lead
480 # to errors when s is Unicode and record.exc_text is str
481 # See issue 8924
482 s = s + record.exc_text.decode(sys.getfilesystemencoding())
483 return s
486 # The default formatter to use when no other is specified
488 _defaultFormatter = Formatter()
490 class BufferingFormatter(object):
492 A formatter suitable for formatting a number of records.
494 def __init__(self, linefmt=None):
496 Optionally specify a formatter which will be used to format each
497 individual record.
499 if linefmt:
500 self.linefmt = linefmt
501 else:
502 self.linefmt = _defaultFormatter
504 def formatHeader(self, records):
506 Return the header string for the specified records.
508 return ""
510 def formatFooter(self, records):
512 Return the footer string for the specified records.
514 return ""
516 def format(self, records):
518 Format the specified records and return the result as a string.
520 rv = ""
521 if len(records) > 0:
522 rv = rv + self.formatHeader(records)
523 for record in records:
524 rv = rv + self.linefmt.format(record)
525 rv = rv + self.formatFooter(records)
526 return rv
528 #---------------------------------------------------------------------------
529 # Filter classes and functions
530 #---------------------------------------------------------------------------
532 class Filter(object):
534 Filter instances are used to perform arbitrary filtering of LogRecords.
536 Loggers and Handlers can optionally use Filter instances to filter
537 records as desired. The base filter class only allows events which are
538 below a certain point in the logger hierarchy. For example, a filter
539 initialized with "A.B" will allow events logged by loggers "A.B",
540 "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
541 initialized with the empty string, all events are passed.
543 def __init__(self, name=''):
545 Initialize a filter.
547 Initialize with the name of the logger which, together with its
548 children, will have its events allowed through the filter. If no
549 name is specified, allow every event.
551 self.name = name
552 self.nlen = len(name)
554 def filter(self, record):
556 Determine if the specified record is to be logged.
558 Is the specified record to be logged? Returns 0 for no, nonzero for
559 yes. If deemed appropriate, the record may be modified in-place.
561 if self.nlen == 0:
562 return 1
563 elif self.name == record.name:
564 return 1
565 elif record.name.find(self.name, 0, self.nlen) != 0:
566 return 0
567 return (record.name[self.nlen] == ".")
569 class Filterer(object):
571 A base class for loggers and handlers which allows them to share
572 common code.
574 def __init__(self):
576 Initialize the list of filters to be an empty list.
578 self.filters = []
580 def addFilter(self, filter):
582 Add the specified filter to this handler.
584 if not (filter in self.filters):
585 self.filters.append(filter)
587 def removeFilter(self, filter):
589 Remove the specified filter from this handler.
591 if filter in self.filters:
592 self.filters.remove(filter)
594 def filter(self, record):
596 Determine if a record is loggable by consulting all the filters.
598 The default is to allow the record to be logged; any filter can veto
599 this and the record is then dropped. Returns a zero value if a record
600 is to be dropped, else non-zero.
602 rv = 1
603 for f in self.filters:
604 if not f.filter(record):
605 rv = 0
606 break
607 return rv
609 #---------------------------------------------------------------------------
610 # Handler classes and functions
611 #---------------------------------------------------------------------------
613 _handlers = weakref.WeakValueDictionary() #map of handler names to handlers
614 _handlerList = [] # added to allow handlers to be removed in reverse of order initialized
616 def _removeHandlerRef(wr):
618 Remove a handler reference from the internal cleanup list.
620 _acquireLock()
621 try:
622 if wr in _handlerList:
623 _handlerList.remove(wr)
624 finally:
625 _releaseLock()
627 def _addHandlerRef(handler):
629 Add a handler to the internal cleanup list using a weak reference.
631 _acquireLock()
632 try:
633 _handlerList.append(weakref.ref(handler, _removeHandlerRef))
634 finally:
635 _releaseLock()
637 class Handler(Filterer):
639 Handler instances dispatch logging events to specific destinations.
641 The base handler class. Acts as a placeholder which defines the Handler
642 interface. Handlers can optionally use Formatter instances to format
643 records as desired. By default, no formatter is specified; in this case,
644 the 'raw' message as determined by record.message is logged.
646 def __init__(self, level=NOTSET):
648 Initializes the instance - basically setting the formatter to None
649 and the filter list to empty.
651 Filterer.__init__(self)
652 self._name = None
653 self.level = _checkLevel(level)
654 self.formatter = None
655 # Add the handler to the global _handlerList (for cleanup on shutdown)
656 _addHandlerRef(self)
657 self.createLock()
659 def get_name(self):
660 return self._name
662 def set_name(self, name):
663 _acquireLock()
664 try:
665 if self._name in _handlers:
666 del _handlers[self._name]
667 self._name = name
668 if name:
669 _handlers[name] = self
670 finally:
671 _releaseLock()
673 name = property(get_name, set_name)
675 def createLock(self):
677 Acquire a thread lock for serializing access to the underlying I/O.
679 if thread:
680 self.lock = threading.RLock()
681 else:
682 self.lock = None
684 def acquire(self):
686 Acquire the I/O thread lock.
688 if self.lock:
689 self.lock.acquire()
691 def release(self):
693 Release the I/O thread lock.
695 if self.lock:
696 self.lock.release()
698 def setLevel(self, level):
700 Set the logging level of this handler.
702 self.level = _checkLevel(level)
704 def format(self, record):
706 Format the specified record.
708 If a formatter is set, use it. Otherwise, use the default formatter
709 for the module.
711 if self.formatter:
712 fmt = self.formatter
713 else:
714 fmt = _defaultFormatter
715 return fmt.format(record)
717 def emit(self, record):
719 Do whatever it takes to actually log the specified logging record.
721 This version is intended to be implemented by subclasses and so
722 raises a NotImplementedError.
724 raise NotImplementedError('emit must be implemented '
725 'by Handler subclasses')
727 def handle(self, record):
729 Conditionally emit the specified logging record.
731 Emission depends on filters which may have been added to the handler.
732 Wrap the actual emission of the record with acquisition/release of
733 the I/O thread lock. Returns whether the filter passed the record for
734 emission.
736 rv = self.filter(record)
737 if rv:
738 self.acquire()
739 try:
740 self.emit(record)
741 finally:
742 self.release()
743 return rv
745 def setFormatter(self, fmt):
747 Set the formatter for this handler.
749 self.formatter = fmt
751 def flush(self):
753 Ensure all logging output has been flushed.
755 This version does nothing and is intended to be implemented by
756 subclasses.
758 pass
760 def close(self):
762 Tidy up any resources used by the handler.
764 This version removes the handler from an internal map of handlers,
765 _handlers, which is used for handler lookup by name. Subclasses
766 should ensure that this gets called from overridden close()
767 methods.
769 #get the module data lock, as we're updating a shared structure.
770 _acquireLock()
771 try: #unlikely to raise an exception, but you never know...
772 if self._name and self._name in _handlers:
773 del _handlers[self._name]
774 finally:
775 _releaseLock()
777 def handleError(self, record):
779 Handle errors which occur during an emit() call.
781 This method should be called from handlers when an exception is
782 encountered during an emit() call. If raiseExceptions is false,
783 exceptions get silently ignored. This is what is mostly wanted
784 for a logging system - most users will not care about errors in
785 the logging system, they are more interested in application errors.
786 You could, however, replace this with a custom handler if you wish.
787 The record which was being processed is passed in to this method.
789 if raiseExceptions:
790 ei = sys.exc_info()
791 try:
792 traceback.print_exception(ei[0], ei[1], ei[2],
793 None, sys.stderr)
794 sys.stderr.write('Logged from file %s, line %s\n' % (
795 record.filename, record.lineno))
796 except IOError:
797 pass # see issue 5971
798 finally:
799 del ei
801 class StreamHandler(Handler):
803 A handler class which writes logging records, appropriately formatted,
804 to a stream. Note that this class does not close the stream, as
805 sys.stdout or sys.stderr may be used.
808 def __init__(self, stream=None):
810 Initialize the handler.
812 If stream is not specified, sys.stderr is used.
814 Handler.__init__(self)
815 if stream is None:
816 stream = sys.stderr
817 self.stream = stream
819 def flush(self):
821 Flushes the stream.
823 if self.stream and hasattr(self.stream, "flush"):
824 self.stream.flush()
826 def emit(self, record):
828 Emit a record.
830 If a formatter is specified, it is used to format the record.
831 The record is then written to the stream with a trailing newline. If
832 exception information is present, it is formatted using
833 traceback.print_exception and appended to the stream. If the stream
834 has an 'encoding' attribute, it is used to determine how to do the
835 output to the stream.
837 try:
838 msg = self.format(record)
839 stream = self.stream
840 fs = "%s\n"
841 if not _unicode: #if no unicode support...
842 stream.write(fs % msg)
843 else:
844 try:
845 if (isinstance(msg, unicode) and
846 getattr(stream, 'encoding', None)):
847 ufs = fs.decode(stream.encoding)
848 try:
849 stream.write(ufs % msg)
850 except UnicodeEncodeError:
851 #Printing to terminals sometimes fails. For example,
852 #with an encoding of 'cp1251', the above write will
853 #work if written to a stream opened or wrapped by
854 #the codecs module, but fail when writing to a
855 #terminal even when the codepage is set to cp1251.
856 #An extra encoding step seems to be needed.
857 stream.write((ufs % msg).encode(stream.encoding))
858 else:
859 stream.write(fs % msg)
860 except UnicodeError:
861 stream.write(fs % msg.encode("UTF-8"))
862 self.flush()
863 except (KeyboardInterrupt, SystemExit):
864 raise
865 except:
866 self.handleError(record)
868 class FileHandler(StreamHandler):
870 A handler class which writes formatted logging records to disk files.
872 def __init__(self, filename, mode='a', encoding=None, delay=0):
874 Open the specified file and use it as the stream for logging.
876 #keep the absolute path, otherwise derived classes which use this
877 #may come a cropper when the current directory changes
878 if codecs is None:
879 encoding = None
880 self.baseFilename = os.path.abspath(filename)
881 self.mode = mode
882 self.encoding = encoding
883 if delay:
884 #We don't open the stream, but we still need to call the
885 #Handler constructor to set level, formatter, lock etc.
886 Handler.__init__(self)
887 self.stream = None
888 else:
889 StreamHandler.__init__(self, self._open())
891 def close(self):
893 Closes the stream.
895 if self.stream:
896 self.flush()
897 if hasattr(self.stream, "close"):
898 self.stream.close()
899 StreamHandler.close(self)
900 self.stream = None
902 def _open(self):
904 Open the current base file with the (original) mode and encoding.
905 Return the resulting stream.
907 if self.encoding is None:
908 stream = open(self.baseFilename, self.mode)
909 else:
910 stream = codecs.open(self.baseFilename, self.mode, self.encoding)
911 return stream
913 def emit(self, record):
915 Emit a record.
917 If the stream was not opened because 'delay' was specified in the
918 constructor, open it before calling the superclass's emit.
920 if self.stream is None:
921 self.stream = self._open()
922 StreamHandler.emit(self, record)
924 #---------------------------------------------------------------------------
925 # Manager classes and functions
926 #---------------------------------------------------------------------------
928 class PlaceHolder(object):
930 PlaceHolder instances are used in the Manager logger hierarchy to take
931 the place of nodes for which no loggers have been defined. This class is
932 intended for internal use only and not as part of the public API.
934 def __init__(self, alogger):
936 Initialize with the specified logger being a child of this placeholder.
938 #self.loggers = [alogger]
939 self.loggerMap = { alogger : None }
941 def append(self, alogger):
943 Add the specified logger as a child of this placeholder.
945 #if alogger not in self.loggers:
946 if alogger not in self.loggerMap:
947 #self.loggers.append(alogger)
948 self.loggerMap[alogger] = None
951 # Determine which class to use when instantiating loggers.
953 _loggerClass = None
955 def setLoggerClass(klass):
957 Set the class to be used when instantiating a logger. The class should
958 define __init__() such that only a name argument is required, and the
959 __init__() should call Logger.__init__()
961 if klass != Logger:
962 if not issubclass(klass, Logger):
963 raise TypeError("logger not derived from logging.Logger: "
964 + klass.__name__)
965 global _loggerClass
966 _loggerClass = klass
968 def getLoggerClass():
970 Return the class to be used when instantiating a logger.
973 return _loggerClass
975 class Manager(object):
977 There is [under normal circumstances] just one Manager instance, which
978 holds the hierarchy of loggers.
980 def __init__(self, rootnode):
982 Initialize the manager with the root node of the logger hierarchy.
984 self.root = rootnode
985 self.disable = 0
986 self.emittedNoHandlerWarning = 0
987 self.loggerDict = {}
988 self.loggerClass = None
990 def getLogger(self, name):
992 Get a logger with the specified name (channel name), creating it
993 if it doesn't yet exist. This name is a dot-separated hierarchical
994 name, such as "a", "a.b", "a.b.c" or similar.
996 If a PlaceHolder existed for the specified name [i.e. the logger
997 didn't exist but a child of it did], replace it with the created
998 logger and fix up the parent/child references which pointed to the
999 placeholder to now point to the logger.
1001 rv = None
1002 _acquireLock()
1003 try:
1004 if name in self.loggerDict:
1005 rv = self.loggerDict[name]
1006 if isinstance(rv, PlaceHolder):
1007 ph = rv
1008 rv = (self.loggerClass or _loggerClass)(name)
1009 rv.manager = self
1010 self.loggerDict[name] = rv
1011 self._fixupChildren(ph, rv)
1012 self._fixupParents(rv)
1013 else:
1014 rv = (self.loggerClass or _loggerClass)(name)
1015 rv.manager = self
1016 self.loggerDict[name] = rv
1017 self._fixupParents(rv)
1018 finally:
1019 _releaseLock()
1020 return rv
1022 def setLoggerClass(self, klass):
1024 Set the class to be used when instantiating a logger with this Manager.
1026 if klass != Logger:
1027 if not issubclass(klass, Logger):
1028 raise TypeError("logger not derived from logging.Logger: "
1029 + klass.__name__)
1030 self.loggerClass = klass
1032 def _fixupParents(self, alogger):
1034 Ensure that there are either loggers or placeholders all the way
1035 from the specified logger to the root of the logger hierarchy.
1037 name = alogger.name
1038 i = name.rfind(".")
1039 rv = None
1040 while (i > 0) and not rv:
1041 substr = name[:i]
1042 if substr not in self.loggerDict:
1043 self.loggerDict[substr] = PlaceHolder(alogger)
1044 else:
1045 obj = self.loggerDict[substr]
1046 if isinstance(obj, Logger):
1047 rv = obj
1048 else:
1049 assert isinstance(obj, PlaceHolder)
1050 obj.append(alogger)
1051 i = name.rfind(".", 0, i - 1)
1052 if not rv:
1053 rv = self.root
1054 alogger.parent = rv
1056 def _fixupChildren(self, ph, alogger):
1058 Ensure that children of the placeholder ph are connected to the
1059 specified logger.
1061 name = alogger.name
1062 namelen = len(name)
1063 for c in ph.loggerMap.keys():
1064 #The if means ... if not c.parent.name.startswith(nm)
1065 if c.parent.name[:namelen] != name:
1066 alogger.parent = c.parent
1067 c.parent = alogger
1069 #---------------------------------------------------------------------------
1070 # Logger classes and functions
1071 #---------------------------------------------------------------------------
1073 class Logger(Filterer):
1075 Instances of the Logger class represent a single logging channel. A
1076 "logging channel" indicates an area of an application. Exactly how an
1077 "area" is defined is up to the application developer. Since an
1078 application can have any number of areas, logging channels are identified
1079 by a unique string. Application areas can be nested (e.g. an area
1080 of "input processing" might include sub-areas "read CSV files", "read
1081 XLS files" and "read Gnumeric files"). To cater for this natural nesting,
1082 channel names are organized into a namespace hierarchy where levels are
1083 separated by periods, much like the Java or Python package namespace. So
1084 in the instance given above, channel names might be "input" for the upper
1085 level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
1086 There is no arbitrary limit to the depth of nesting.
1088 def __init__(self, name, level=NOTSET):
1090 Initialize the logger with a name and an optional level.
1092 Filterer.__init__(self)
1093 self.name = name
1094 self.level = _checkLevel(level)
1095 self.parent = None
1096 self.propagate = 1
1097 self.handlers = []
1098 self.disabled = 0
1100 def setLevel(self, level):
1102 Set the logging level of this logger.
1104 self.level = _checkLevel(level)
1106 def debug(self, msg, *args, **kwargs):
1108 Log 'msg % args' with severity 'DEBUG'.
1110 To pass exception information, use the keyword argument exc_info with
1111 a true value, e.g.
1113 logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
1115 if self.isEnabledFor(DEBUG):
1116 self._log(DEBUG, msg, args, **kwargs)
1118 def info(self, msg, *args, **kwargs):
1120 Log 'msg % args' with severity 'INFO'.
1122 To pass exception information, use the keyword argument exc_info with
1123 a true value, e.g.
1125 logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
1127 if self.isEnabledFor(INFO):
1128 self._log(INFO, msg, args, **kwargs)
1130 def warning(self, msg, *args, **kwargs):
1132 Log 'msg % args' with severity 'WARNING'.
1134 To pass exception information, use the keyword argument exc_info with
1135 a true value, e.g.
1137 logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
1139 if self.isEnabledFor(WARNING):
1140 self._log(WARNING, msg, args, **kwargs)
1142 warn = warning
1144 def error(self, msg, *args, **kwargs):
1146 Log 'msg % args' with severity 'ERROR'.
1148 To pass exception information, use the keyword argument exc_info with
1149 a true value, e.g.
1151 logger.error("Houston, we have a %s", "major problem", exc_info=1)
1153 if self.isEnabledFor(ERROR):
1154 self._log(ERROR, msg, args, **kwargs)
1156 def exception(self, msg, *args):
1158 Convenience method for logging an ERROR with exception information.
1160 self.error(msg, exc_info=1, *args)
1162 def critical(self, msg, *args, **kwargs):
1164 Log 'msg % args' with severity 'CRITICAL'.
1166 To pass exception information, use the keyword argument exc_info with
1167 a true value, e.g.
1169 logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
1171 if self.isEnabledFor(CRITICAL):
1172 self._log(CRITICAL, msg, args, **kwargs)
1174 fatal = critical
1176 def log(self, level, msg, *args, **kwargs):
1178 Log 'msg % args' with the integer severity 'level'.
1180 To pass exception information, use the keyword argument exc_info with
1181 a true value, e.g.
1183 logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1185 if not isinstance(level, int):
1186 if raiseExceptions:
1187 raise TypeError("level must be an integer")
1188 else:
1189 return
1190 if self.isEnabledFor(level):
1191 self._log(level, msg, args, **kwargs)
1193 def findCaller(self):
1195 Find the stack frame of the caller so that we can note the source
1196 file name, line number and function name.
1198 f = currentframe()
1199 #On some versions of IronPython, currentframe() returns None if
1200 #IronPython isn't run with -X:Frames.
1201 if f is not None:
1202 f = f.f_back
1203 rv = "(unknown file)", 0, "(unknown function)"
1204 while hasattr(f, "f_code"):
1205 co = f.f_code
1206 filename = os.path.normcase(co.co_filename)
1207 if filename == _srcfile:
1208 f = f.f_back
1209 continue
1210 rv = (filename, f.f_lineno, co.co_name)
1211 break
1212 return rv
1214 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
1216 A factory method which can be overridden in subclasses to create
1217 specialized LogRecords.
1219 rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func)
1220 if extra is not None:
1221 for key in extra:
1222 if (key in ["message", "asctime"]) or (key in rv.__dict__):
1223 raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1224 rv.__dict__[key] = extra[key]
1225 return rv
1227 def _log(self, level, msg, args, exc_info=None, extra=None):
1229 Low-level logging routine which creates a LogRecord and then calls
1230 all the handlers of this logger to handle the record.
1232 if _srcfile:
1233 #IronPython doesn't track Python frames, so findCaller throws an
1234 #exception on some versions of IronPython. We trap it here so that
1235 #IronPython can use logging.
1236 try:
1237 fn, lno, func = self.findCaller()
1238 except ValueError:
1239 fn, lno, func = "(unknown file)", 0, "(unknown function)"
1240 else:
1241 fn, lno, func = "(unknown file)", 0, "(unknown function)"
1242 if exc_info:
1243 if not isinstance(exc_info, tuple):
1244 exc_info = sys.exc_info()
1245 record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
1246 self.handle(record)
1248 def handle(self, record):
1250 Call the handlers for the specified record.
1252 This method is used for unpickled records received from a socket, as
1253 well as those created locally. Logger-level filtering is applied.
1255 if (not self.disabled) and self.filter(record):
1256 self.callHandlers(record)
1258 def addHandler(self, hdlr):
1260 Add the specified handler to this logger.
1262 if not (hdlr in self.handlers):
1263 self.handlers.append(hdlr)
1265 def removeHandler(self, hdlr):
1267 Remove the specified handler from this logger.
1269 if hdlr in self.handlers:
1270 #hdlr.close()
1271 hdlr.acquire()
1272 try:
1273 self.handlers.remove(hdlr)
1274 finally:
1275 hdlr.release()
1277 def callHandlers(self, record):
1279 Pass a record to all relevant handlers.
1281 Loop through all handlers for this logger and its parents in the
1282 logger hierarchy. If no handler was found, output a one-off error
1283 message to sys.stderr. Stop searching up the hierarchy whenever a
1284 logger with the "propagate" attribute set to zero is found - that
1285 will be the last logger whose handlers are called.
1287 c = self
1288 found = 0
1289 while c:
1290 for hdlr in c.handlers:
1291 found = found + 1
1292 if record.levelno >= hdlr.level:
1293 hdlr.handle(record)
1294 if not c.propagate:
1295 c = None #break out
1296 else:
1297 c = c.parent
1298 if (found == 0) and raiseExceptions and not self.manager.emittedNoHandlerWarning:
1299 sys.stderr.write("No handlers could be found for logger"
1300 " \"%s\"\n" % self.name)
1301 self.manager.emittedNoHandlerWarning = 1
1303 def getEffectiveLevel(self):
1305 Get the effective level for this logger.
1307 Loop through this logger and its parents in the logger hierarchy,
1308 looking for a non-zero logging level. Return the first one found.
1310 logger = self
1311 while logger:
1312 if logger.level:
1313 return logger.level
1314 logger = logger.parent
1315 return NOTSET
1317 def isEnabledFor(self, level):
1319 Is this logger enabled for level 'level'?
1321 if self.manager.disable >= level:
1322 return 0
1323 return level >= self.getEffectiveLevel()
1325 def getChild(self, suffix):
1327 Get a logger which is a descendant to this one.
1329 This is a convenience method, such that
1331 logging.getLogger('abc').getChild('def.ghi')
1333 is the same as
1335 logging.getLogger('abc.def.ghi')
1337 It's useful, for example, when the parent logger is named using
1338 __name__ rather than a literal string.
1340 if self.root is not self:
1341 suffix = '.'.join((self.name, suffix))
1342 return self.manager.getLogger(suffix)
1344 class RootLogger(Logger):
1346 A root logger is not that different to any other logger, except that
1347 it must have a logging level and there is only one instance of it in
1348 the hierarchy.
1350 def __init__(self, level):
1352 Initialize the logger with the name "root".
1354 Logger.__init__(self, "root", level)
1356 _loggerClass = Logger
1358 class LoggerAdapter(object):
1360 An adapter for loggers which makes it easier to specify contextual
1361 information in logging output.
1364 def __init__(self, logger, extra):
1366 Initialize the adapter with a logger and a dict-like object which
1367 provides contextual information. This constructor signature allows
1368 easy stacking of LoggerAdapters, if so desired.
1370 You can effectively pass keyword arguments as shown in the
1371 following example:
1373 adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1375 self.logger = logger
1376 self.extra = extra
1378 def process(self, msg, kwargs):
1380 Process the logging message and keyword arguments passed in to
1381 a logging call to insert contextual information. You can either
1382 manipulate the message itself, the keyword args or both. Return
1383 the message and kwargs modified (or not) to suit your needs.
1385 Normally, you'll only need to override this one method in a
1386 LoggerAdapter subclass for your specific needs.
1388 kwargs["extra"] = self.extra
1389 return msg, kwargs
1391 def debug(self, msg, *args, **kwargs):
1393 Delegate a debug call to the underlying logger, after adding
1394 contextual information from this adapter instance.
1396 msg, kwargs = self.process(msg, kwargs)
1397 self.logger.debug(msg, *args, **kwargs)
1399 def info(self, msg, *args, **kwargs):
1401 Delegate an info call to the underlying logger, after adding
1402 contextual information from this adapter instance.
1404 msg, kwargs = self.process(msg, kwargs)
1405 self.logger.info(msg, *args, **kwargs)
1407 def warning(self, msg, *args, **kwargs):
1409 Delegate a warning call to the underlying logger, after adding
1410 contextual information from this adapter instance.
1412 msg, kwargs = self.process(msg, kwargs)
1413 self.logger.warning(msg, *args, **kwargs)
1415 def error(self, msg, *args, **kwargs):
1417 Delegate an error call to the underlying logger, after adding
1418 contextual information from this adapter instance.
1420 msg, kwargs = self.process(msg, kwargs)
1421 self.logger.error(msg, *args, **kwargs)
1423 def exception(self, msg, *args, **kwargs):
1425 Delegate an exception call to the underlying logger, after adding
1426 contextual information from this adapter instance.
1428 msg, kwargs = self.process(msg, kwargs)
1429 kwargs["exc_info"] = 1
1430 self.logger.error(msg, *args, **kwargs)
1432 def critical(self, msg, *args, **kwargs):
1434 Delegate a critical call to the underlying logger, after adding
1435 contextual information from this adapter instance.
1437 msg, kwargs = self.process(msg, kwargs)
1438 self.logger.critical(msg, *args, **kwargs)
1440 def log(self, level, msg, *args, **kwargs):
1442 Delegate a log call to the underlying logger, after adding
1443 contextual information from this adapter instance.
1445 msg, kwargs = self.process(msg, kwargs)
1446 self.logger.log(level, msg, *args, **kwargs)
1448 def isEnabledFor(self, level):
1450 See if the underlying logger is enabled for the specified level.
1452 return self.logger.isEnabledFor(level)
1454 root = RootLogger(WARNING)
1455 Logger.root = root
1456 Logger.manager = Manager(Logger.root)
1458 #---------------------------------------------------------------------------
1459 # Configuration classes and functions
1460 #---------------------------------------------------------------------------
1462 BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
1464 def basicConfig(**kwargs):
1466 Do basic configuration for the logging system.
1468 This function does nothing if the root logger already has handlers
1469 configured. It is a convenience method intended for use by simple scripts
1470 to do one-shot configuration of the logging package.
1472 The default behaviour is to create a StreamHandler which writes to
1473 sys.stderr, set a formatter using the BASIC_FORMAT format string, and
1474 add the handler to the root logger.
1476 A number of optional keyword arguments may be specified, which can alter
1477 the default behaviour.
1479 filename Specifies that a FileHandler be created, using the specified
1480 filename, rather than a StreamHandler.
1481 filemode Specifies the mode to open the file, if filename is specified
1482 (if filemode is unspecified, it defaults to 'a').
1483 format Use the specified format string for the handler.
1484 datefmt Use the specified date/time format.
1485 level Set the root logger level to the specified level.
1486 stream Use the specified stream to initialize the StreamHandler. Note
1487 that this argument is incompatible with 'filename' - if both
1488 are present, 'stream' is ignored.
1490 Note that you could specify a stream created using open(filename, mode)
1491 rather than passing the filename and mode in. However, it should be
1492 remembered that StreamHandler does not close its stream (since it may be
1493 using sys.stdout or sys.stderr), whereas FileHandler closes its stream
1494 when the handler is closed.
1496 if len(root.handlers) == 0:
1497 filename = kwargs.get("filename")
1498 if filename:
1499 mode = kwargs.get("filemode", 'a')
1500 hdlr = FileHandler(filename, mode)
1501 else:
1502 stream = kwargs.get("stream")
1503 hdlr = StreamHandler(stream)
1504 fs = kwargs.get("format", BASIC_FORMAT)
1505 dfs = kwargs.get("datefmt", None)
1506 fmt = Formatter(fs, dfs)
1507 hdlr.setFormatter(fmt)
1508 root.addHandler(hdlr)
1509 level = kwargs.get("level")
1510 if level is not None:
1511 root.setLevel(level)
1513 #---------------------------------------------------------------------------
1514 # Utility functions at module level.
1515 # Basically delegate everything to the root logger.
1516 #---------------------------------------------------------------------------
1518 def getLogger(name=None):
1520 Return a logger with the specified name, creating it if necessary.
1522 If no name is specified, return the root logger.
1524 if name:
1525 return Logger.manager.getLogger(name)
1526 else:
1527 return root
1529 #def getRootLogger():
1530 # """
1531 # Return the root logger.
1533 # Note that getLogger('') now does the same thing, so this function is
1534 # deprecated and may disappear in the future.
1535 # """
1536 # return root
1538 def critical(msg, *args, **kwargs):
1540 Log a message with severity 'CRITICAL' on the root logger.
1542 if len(root.handlers) == 0:
1543 basicConfig()
1544 root.critical(msg, *args, **kwargs)
1546 fatal = critical
1548 def error(msg, *args, **kwargs):
1550 Log a message with severity 'ERROR' on the root logger.
1552 if len(root.handlers) == 0:
1553 basicConfig()
1554 root.error(msg, *args, **kwargs)
1556 def exception(msg, *args):
1558 Log a message with severity 'ERROR' on the root logger,
1559 with exception information.
1561 error(msg, exc_info=1, *args)
1563 def warning(msg, *args, **kwargs):
1565 Log a message with severity 'WARNING' on the root logger.
1567 if len(root.handlers) == 0:
1568 basicConfig()
1569 root.warning(msg, *args, **kwargs)
1571 warn = warning
1573 def info(msg, *args, **kwargs):
1575 Log a message with severity 'INFO' on the root logger.
1577 if len(root.handlers) == 0:
1578 basicConfig()
1579 root.info(msg, *args, **kwargs)
1581 def debug(msg, *args, **kwargs):
1583 Log a message with severity 'DEBUG' on the root logger.
1585 if len(root.handlers) == 0:
1586 basicConfig()
1587 root.debug(msg, *args, **kwargs)
1589 def log(level, msg, *args, **kwargs):
1591 Log 'msg % args' with the integer severity 'level' on the root logger.
1593 if len(root.handlers) == 0:
1594 basicConfig()
1595 root.log(level, msg, *args, **kwargs)
1597 def disable(level):
1599 Disable all logging calls of severity 'level' and below.
1601 root.manager.disable = level
1603 def shutdown(handlerList=_handlerList):
1605 Perform any cleanup actions in the logging system (e.g. flushing
1606 buffers).
1608 Should be called at application exit.
1610 for wr in reversed(handlerList[:]):
1611 #errors might occur, for example, if files are locked
1612 #we just ignore them if raiseExceptions is not set
1613 try:
1614 h = wr()
1615 h.flush()
1616 h.close()
1617 except:
1618 if raiseExceptions:
1619 raise
1620 #else, swallow
1622 #Let's try and shutdown automatically on application exit...
1623 import atexit
1624 atexit.register(shutdown)
1626 # Null handler
1628 class NullHandler(Handler):
1630 This handler does nothing. It's intended to be used to avoid the
1631 "No handlers could be found for logger XXX" one-off warning. This is
1632 important for library code, which may contain code to log events. If a user
1633 of the library does not configure logging, the one-off warning might be
1634 produced; to avoid this, the library developer simply needs to instantiate
1635 a NullHandler and add it to the top-level logger of the library module or
1636 package.
1638 def emit(self, record):
1639 pass
1641 # Warnings integration
1643 _warnings_showwarning = None
1645 def _showwarning(message, category, filename, lineno, file=None, line=None):
1647 Implementation of showwarnings which redirects to logging, which will first
1648 check to see if the file parameter is None. If a file is specified, it will
1649 delegate to the original warnings implementation of showwarning. Otherwise,
1650 it will call warnings.formatwarning and will log the resulting string to a
1651 warnings logger named "py.warnings" with level logging.WARNING.
1653 if file is not None:
1654 if _warnings_showwarning is not None:
1655 _warnings_showwarning(message, category, filename, lineno, file, line)
1656 else:
1657 s = warnings.formatwarning(message, category, filename, lineno, line)
1658 logger = getLogger("py.warnings")
1659 if not logger.handlers:
1660 logger.addHandler(NullHandler())
1661 logger.warning("%s", s)
1663 def captureWarnings(capture):
1665 If capture is true, redirect all warnings to the logging package.
1666 If capture is False, ensure that warnings are not redirected to logging
1667 but to their original destinations.
1669 global _warnings_showwarning
1670 if capture:
1671 if _warnings_showwarning is None:
1672 _warnings_showwarning = warnings.showwarning
1673 warnings.showwarning = _showwarning
1674 else:
1675 if _warnings_showwarning is not None:
1676 warnings.showwarning = _warnings_showwarning
1677 _warnings_showwarning = None