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.
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!
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']
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 #---------------------------------------------------------------------------
62 # _srcfile is used when walking the stack to check when we've got the first
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'
71 _srcfile
= os
.path
.normcase(_srcfile
)
73 # next bit filched from 1.5.2's inspect.py
75 """Return the frame object for the caller's stack frame."""
79 return sys
.exc_info()[2].tb_frame
.f_back
81 if hasattr(sys
, '_getframe'): currentframe
= lambda: sys
._getframe
(3)
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"):
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
103 # If you don't want threading information in the log, set this to zero
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
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.
138 CRITICAL
: 'CRITICAL',
144 'CRITICAL' : CRITICAL
,
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.
176 try: #unlikely to cause an exception, but you never know...
177 _levelNames
[level
] = levelName
178 _levelNames
[levelName
] = level
182 def _checkLevel(level
):
183 if isinstance(level
, int):
185 elif str(level
) == level
:
186 if level
not in _levelNames
:
187 raise ValueError("Unknown level: %r" % level
)
188 rv
= _levelNames
[level
]
190 raise TypeError("Level not an integer or a valid string: %r" % level
)
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.
206 _lock
= threading
.RLock()
212 Acquire the module-level lock for serializing access to shared data.
214 This should be released with _releaseLock().
221 Release the module-level lock acquired by calling _acquireLock().
226 #---------------------------------------------------------------------------
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.
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
263 if args
and len(args
) == 1 and isinstance(args
[0], dict) and args
[0]:
266 self
.levelname
= getLevelName(level
)
268 self
.pathname
= pathname
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
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
287 self
.threadName
= None
288 if not logMultiprocessing
:
289 self
.processName
= None
291 self
.processName
= 'MainProcess'
292 mp
= sys
.modules
.get('multiprocessing')
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
299 self
.processName
= mp
.current_process().name
300 except StandardError:
302 if logProcesses
and hasattr(os
, 'getpid'):
303 self
.process
= os
.getpid()
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...
322 if not isinstance(msg
, basestring
):
326 msg
= self
.msg
#Defer encoding till later
328 msg
= msg
% self
.args
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
338 rv
= LogRecord(None, None, "", 0, "", (), None, None)
339 rv
.__dict
__.update(dict)
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
373 %(funcName)s Function name
374 %(created)f Time when the LogRecord was created (time.time()
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).
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
)
424 s
= time
.strftime(datefmt
, ct
)
426 t
= time
.strftime("%Y-%m-%d %H:%M:%S", ct
)
427 s
= "%s,%03d" % (t
, record
.msecs
)
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
)
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()
466 record
.asctime
= self
.formatTime(record
, self
.datefmt
)
467 s
= self
._fmt
% record
.__dict
__
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
)
477 s
= s
+ record
.exc_text
479 # Sometimes filenames have non-ASCII chars, which can lead
480 # to errors when s is Unicode and record.exc_text is str
482 s
= s
+ record
.exc_text
.decode(sys
.getfilesystemencoding())
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
500 self
.linefmt
= linefmt
502 self
.linefmt
= _defaultFormatter
504 def formatHeader(self
, records
):
506 Return the header string for the specified records.
510 def formatFooter(self
, records
):
512 Return the footer string for the specified records.
516 def format(self
, records
):
518 Format the specified records and return the result as a string.
522 rv
= rv
+ self
.formatHeader(records
)
523 for record
in records
:
524 rv
= rv
+ self
.linefmt
.format(record
)
525 rv
= rv
+ self
.formatFooter(records
)
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
=''):
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.
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.
563 elif self
.name
== record
.name
:
565 elif record
.name
.find(self
.name
, 0, self
.nlen
) != 0:
567 return (record
.name
[self
.nlen
] == ".")
569 class Filterer(object):
571 A base class for loggers and handlers which allows them to share
576 Initialize the list of filters to be an empty list.
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.
603 for f
in self
.filters
:
604 if not f
.filter(record
):
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.
622 if wr
in _handlerList
:
623 _handlerList
.remove(wr
)
627 def _addHandlerRef(handler
):
629 Add a handler to the internal cleanup list using a weak reference.
633 _handlerList
.append(weakref
.ref(handler
, _removeHandlerRef
))
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
)
653 self
.level
= _checkLevel(level
)
654 self
.formatter
= None
655 # Add the handler to the global _handlerList (for cleanup on shutdown)
662 def set_name(self
, name
):
665 if self
._name
in _handlers
:
666 del _handlers
[self
._name
]
669 _handlers
[name
] = self
673 name
= property(get_name
, set_name
)
675 def createLock(self
):
677 Acquire a thread lock for serializing access to the underlying I/O.
680 self
.lock
= threading
.RLock()
686 Acquire the I/O thread lock.
693 Release the I/O thread lock.
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
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
736 rv
= self
.filter(record
)
745 def setFormatter(self
, fmt
):
747 Set the formatter for this handler.
753 Ensure all logging output has been flushed.
755 This version does nothing and is intended to be implemented by
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()
769 #get the module data lock, as we're updating a shared structure.
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
]
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.
792 traceback
.print_exception(ei
[0], ei
[1], ei
[2],
794 sys
.stderr
.write('Logged from file %s, line %s\n' % (
795 record
.filename
, record
.lineno
))
797 pass # see issue 5971
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
)
823 if self
.stream
and hasattr(self
.stream
, "flush"):
826 def emit(self
, 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.
838 msg
= self
.format(record
)
841 if not _unicode
: #if no unicode support...
842 stream
.write(fs
% msg
)
845 if (isinstance(msg
, unicode) and
846 getattr(stream
, 'encoding', None)):
847 ufs
= fs
.decode(stream
.encoding
)
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
))
859 stream
.write(fs
% msg
)
861 stream
.write(fs
% msg
.encode("UTF-8"))
863 except (KeyboardInterrupt, SystemExit):
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
880 self
.baseFilename
= os
.path
.abspath(filename
)
882 self
.encoding
= encoding
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
)
889 StreamHandler
.__init
__(self
, self
._open
())
897 if hasattr(self
.stream
, "close"):
899 StreamHandler
.close(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
)
910 stream
= codecs
.open(self
.baseFilename
, self
.mode
, self
.encoding
)
913 def emit(self
, 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.
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__()
962 if not issubclass(klass
, Logger
):
963 raise TypeError("logger not derived from logging.Logger: "
968 def getLoggerClass():
970 Return the class to be used when instantiating a logger.
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.
986 self
.emittedNoHandlerWarning
= 0
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.
1004 if name
in self
.loggerDict
:
1005 rv
= self
.loggerDict
[name
]
1006 if isinstance(rv
, PlaceHolder
):
1008 rv
= (self
.loggerClass
or _loggerClass
)(name
)
1010 self
.loggerDict
[name
] = rv
1011 self
._fixupChildren
(ph
, rv
)
1012 self
._fixupParents
(rv
)
1014 rv
= (self
.loggerClass
or _loggerClass
)(name
)
1016 self
.loggerDict
[name
] = rv
1017 self
._fixupParents
(rv
)
1022 def setLoggerClass(self
, klass
):
1024 Set the class to be used when instantiating a logger with this Manager.
1027 if not issubclass(klass
, Logger
):
1028 raise TypeError("logger not derived from logging.Logger: "
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.
1040 while (i
> 0) and not rv
:
1042 if substr
not in self
.loggerDict
:
1043 self
.loggerDict
[substr
] = PlaceHolder(alogger
)
1045 obj
= self
.loggerDict
[substr
]
1046 if isinstance(obj
, Logger
):
1049 assert isinstance(obj
, PlaceHolder
)
1051 i
= name
.rfind(".", 0, i
- 1)
1056 def _fixupChildren(self
, ph
, alogger
):
1058 Ensure that children of the placeholder ph are connected to the
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
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
)
1094 self
.level
= _checkLevel(level
)
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
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
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
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
)
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
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
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
)
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
1183 logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
1185 if not isinstance(level
, int):
1187 raise TypeError("level must be an integer")
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.
1199 #On some versions of IronPython, currentframe() returns None if
1200 #IronPython isn't run with -X:Frames.
1203 rv
= "(unknown file)", 0, "(unknown function)"
1204 while hasattr(f
, "f_code"):
1206 filename
= os
.path
.normcase(co
.co_filename
)
1207 if filename
== _srcfile
:
1210 rv
= (filename
, f
.f_lineno
, co
.co_name
)
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:
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
]
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.
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.
1237 fn
, lno
, func
= self
.findCaller()
1239 fn
, lno
, func
= "(unknown file)", 0, "(unknown function)"
1241 fn
, lno
, func
= "(unknown file)", 0, "(unknown function)"
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
)
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
:
1273 self
.handlers
.remove(hdlr
)
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.
1290 for hdlr
in c
.handlers
:
1292 if record
.levelno
>= hdlr
.level
:
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.
1314 logger
= logger
.parent
1317 def isEnabledFor(self
, level
):
1319 Is this logger enabled for level 'level'?
1321 if self
.manager
.disable
>= level
:
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')
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
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
1373 adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
1375 self
.logger
= logger
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
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
)
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")
1499 mode
= kwargs
.get("filemode", 'a')
1500 hdlr
= FileHandler(filename
, mode
)
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.
1525 return Logger
.manager
.getLogger(name
)
1529 #def getRootLogger():
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.
1538 def critical(msg
, *args
, **kwargs
):
1540 Log a message with severity 'CRITICAL' on the root logger.
1542 if len(root
.handlers
) == 0:
1544 root
.critical(msg
, *args
, **kwargs
)
1548 def error(msg
, *args
, **kwargs
):
1550 Log a message with severity 'ERROR' on the root logger.
1552 if len(root
.handlers
) == 0:
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:
1569 root
.warning(msg
, *args
, **kwargs
)
1573 def info(msg
, *args
, **kwargs
):
1575 Log a message with severity 'INFO' on the root logger.
1577 if len(root
.handlers
) == 0:
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:
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:
1595 root
.log(level
, msg
, *args
, **kwargs
)
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
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
1622 #Let's try and shutdown automatically on application exit...
1624 atexit
.register(shutdown
)
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
1638 def emit(self
, record
):
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
)
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
1671 if _warnings_showwarning
is None:
1672 _warnings_showwarning
= warnings
.showwarning
1673 warnings
.showwarning
= _showwarning
1675 if _warnings_showwarning
is not None:
1676 warnings
.showwarning
= _warnings_showwarning
1677 _warnings_showwarning
= None