Source code: Lib/logging/handlers.py
Important
This page contains only reference information. For tutorials, please see
The following useful handlers are provided in the package. Note that three of the handlers (StreamHandler, FileHandler and NullHandler) are actually defined in the logging module itself, but have been documented here along with the other handlers.
The StreamHandler class, located in the core logging package, sends logging output to streams such as sys.stdout, sys.stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).
Returns a new instance of the StreamHandler class. If stream is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.
If a formatter is specified, it is used to format the record. The record is then written to the stream followed by terminator. If exception information is present, it is formatted using traceback.print_exception() and appended to the stream.
Flushes the stream by calling its flush() method. Note that the close() method is inherited from Handler and so does no output, so an explicit flush() call may be needed at times.
Sets the instance’s stream to the specified value, if it is different. The old stream is flushed before the new stream is set.
stream – The stream that the handler should use.
the old stream, if the stream was changed, or None if it wasn’t.
New in version 3.7.
String used as the terminator when writing a formatted record to a stream. Default value is '\n'.
If you don’t want a newline termination, you can set the handler instance’s terminator attribute to the empty string.
In earlier versions, the terminator was hardcoded as '\n'.
New in version 3.2.
The FileHandler class, located in the core logging package, sends logging output to a disk file. It inherits the output functionality from StreamHandler.
Returns a new instance of the FileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is specified, it’s used to determine how encoding errors are handled.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Closes the file.
Outputs the record to the file.
New in version 3.1.
The NullHandler class, located in the core logging package, does not do any formatting or output. It is essentially a ‘no-op’ handler for use by library developers.
Returns a new instance of the NullHandler class.
This method does nothing.
This method does nothing.
This method returns None for the lock, since there is no underlying I/O to which access needs to be serialized.
See Configuring Logging for a Library for more information on how to use NullHandler.
The WatchedFileHandler class, located in the logging.handlers module, is a FileHandler which watches the file it is logging to. If the file changes, it is closed and reopened using the file name.
A file change can happen because of usage of programs such as newsyslog and logrotate which perform log file rotation. This handler, intended for use under Unix/Linux, watches the file to see if it has changed since the last emit. (A file is deemed to have changed if its device or inode have changed.) If the file has changed, the old file stream is closed, and the file opened to get a new stream.
This handler is not appropriate for use under Windows, because under Windows open log files cannot be moved or renamed - logging opens the files with exclusive locks - and so there is no need for such a handler. Furthermore, ST_INO is not supported under Windows; stat() always returns zero for this value.
Returns a new instance of the WatchedFileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is provided, it determines how encoding errors are handled.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Checks to see if the file has changed. If it has, the existing stream is flushed and closed and the file opened again, typically as a precursor to outputting the record to the file.
New in version 3.6.
Outputs the record to the file, but first calls reopenIfNeeded() to reopen the file if it has changed.
The BaseRotatingHandler class, located in the logging.handlers module, is the base class for the rotating file handlers, RotatingFileHandler and TimedRotatingFileHandler. You should not need to instantiate this class, but it has attributes and methods you may need to override.
The parameters are as for FileHandler. The attributes are:
If this attribute is set to a callable, the rotation_filename() method delegates to this callable. The parameters passed to the callable are those passed to rotation_filename().
Note
The namer function is called quite a few times during rollover, so it should be as simple and as fast as possible. It should also return the same output every time for a given input, otherwise the rollover behaviour may not work as expected.
New in version 3.3.
If this attribute is set to a callable, the rotate() method delegates to this callable. The parameters passed to the callable are those passed to rotate().
New in version 3.3.
Modify the filename of a log file when rotating.
This is provided so that a custom filename can be provided.
The default implementation calls the ‘namer’ attribute of the handler, if it’s callable, passing the default name to it. If the attribute isn’t callable (the default is None), the name is returned unchanged.
default_name – The default name for the log file.
New in version 3.3.
When rotating, rotate the current log.
The default implementation calls the ‘rotator’ attribute of the handler, if it’s callable, passing the source and dest arguments to it. If the attribute isn’t callable (the default is None), the source is simply renamed to the destination.
New in version 3.3.
The reason the attributes exist is to save you having to subclass - you can use the same callables for instances of RotatingFileHandler and TimedRotatingFileHandler. If either the namer or rotator callable raises an exception, this will be handled in the same way as any other exception during an emit() call, i.e. via the handleError() method of the handler.
If you need to make more significant changes to rotation processing, you can override the methods.
For an example, see Using a rotator and namer to customize log rotation processing.
The RotatingFileHandler class, located in the logging.handlers module, supports rotation of disk log files.
Returns a new instance of the RotatingFileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is provided, it determines how encoding errors are handled.
You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length; but if either of maxBytes or backupCount is zero, rollover never occurs, so you generally want to set backupCount to at least 1, and have a non-zero maxBytes. When backupCount is non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., to the filename. For example, with a backupCount of 5 and a base file name of app.log, you would get app.log, app.log.1, app.log.2, up to app.log.5. The file being written to is always app.log. When this file is filled, it is closed and renamed to app.log.1, and if files app.log.1, app.log.2, etc. exist, then they are renamed to app.log.2, app.log.3 etc. respectively.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Does a rollover, as described above.
Outputs the record to the file, catering for rollover as described previously.
The TimedRotatingFileHandler class, located in the logging.handlers module, supports rotation of disk log files at certain timed intervals.
Returns a new instance of the TimedRotatingFileHandler class. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of when and interval.
You can use the when to specify the type of interval. The list of possible values is below. Note that they are not case sensitive.
Value
Type of interval
If/how atTime is used
'S'
Seconds
Ignored
'M'
Minutes
Ignored
'H'
Hours
Ignored
'D'
Days
Ignored
'W0'-'W6'
Weekday (0=Monday)
Used to compute initial rollover time
'midnight'
Roll over at midnight, if atTime not specified, else at time atTime
Used to compute initial rollover time
When using weekday-based rotation, specify ‘W0’ for Monday, ‘W1’ for Tuesday, and so on up to ‘W6’ for Sunday. In this case, the value passed for interval isn’t used.
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.
When computing the next rollover time for the first time (when the handler is created), the last modification time of an existing log file, or else the current time, is used to compute when the next rotation will occur.
If the utc argument is true, times in UTC will be used; otherwise local time is used.
If backupCount is nonzero, at most backupCount files will be kept, and if more would be created when rollover occurs, the oldest one is deleted. The deletion logic uses the interval to determine which files to delete, so changing the interval may leave old files lying around.
If delay is true, then file opening is deferred until the first call to emit().
If atTime is not None, it must be a datetime.time instance which specifies the time of day when rollover occurs, for the cases where rollover is set to happen “at midnight” or “on a particular weekday”. Note that in these cases, the atTime value is effectively used to compute the initial rollover, and subsequent rollovers would be calculated via the normal interval calculation.
If errors is specified, it’s used to determine how encoding errors are handled.
Note
Calculation of the initial rollover time is done when the handler is initialised. Calculation of subsequent rollover times is done only when rollover occurs, and rollover occurs only when emitting output. If this is not kept in mind, it might lead to some confusion. For example, if an interval of “every minute” is set, that does not mean you will always see log files with times (in the filename) separated by a minute; if, during application execution, logging output is generated more frequently than once a minute, then you can expect to see log files with times separated by a minute. If, on the other hand, logging messages are only output once every five minutes (say), then there will be gaps in the file times corresponding to the minutes where no output (and hence no rollover) occurred.
Changed in version 3.4: atTime parameter was added.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Does a rollover, as described above.
Outputs the record to the file, catering for rollover as described above.
The SocketHandler class, located in the logging.handlers module, sends logging output to a network socket. The base class uses a TCP socket.
Returns a new instance of the SocketHandler class intended to communicate with a remote machine whose address is given by host and port.
Changed in version 3.4: If port is specified as None, a Unix domain socket is created using the value in host - otherwise, a TCP socket is created.
Closes the socket.
Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. If the connection was previously lost, re-establishes the connection. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.
Handles an error which has occurred during emit(). The most likely cause is a lost connection. Closes the socket so that we can retry on the next event.
This is a factory method which allows subclasses to define the precise type of socket they want. The default implementation creates a TCP socket (socket.SOCK_STREAM).
Pickles the record’s attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket. The details of this operation are equivalent to:
Note that pickles aren’t completely secure. If you are concerned about security, you may want to override this method to implement a more secure mechanism. For example, you can sign pickles using HMAC and then verify them on the receiving end, or alternatively you can disable unpickling of global objects on the receiving end.
Send a pickled byte-string packet to the socket. The format of the sent byte-string is as described in the documentation for makePickle().
This function allows for partial sends, which can happen when the network is busy.
Tries to create a socket; on failure, uses an exponential back-off algorithm. On initial failure, the handler will drop the message it was trying to send. When subsequent messages are handled by the same instance, it will not try connecting until some time has passed. The default parameters are such that the initial delay is one second, and if after that delay the connection still can’t be made, the handler will double the delay each time up to a maximum of 30 seconds.
This behaviour is controlled by the following handler attributes:
This means that if the remote listener starts up after the handler has been used, you could lose messages (since the handler won’t even attempt a connection until the delay has elapsed, but just silently drop messages during the delay period).
The DatagramHandler class, located in the logging.handlers module, inherits from SocketHandler to support sending logging messages over UDP sockets.
Returns a new instance of the DatagramHandler class intended to communicate with a remote machine whose address is given by host and port.
Changed in version 3.4: If port is specified as None, a Unix domain socket is created using the value in host - otherwise, a UDP socket is created.
Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.
The factory method of SocketHandler is here overridden to create a UDP socket (socket.SOCK_DGRAM).
Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for SocketHandler.makePickle().
The SysLogHandler class, located in the logging.handlers module, supports sending logging messages to a remote or local Unix syslog.
Returns a new instance of the SysLogHandler class intended to communicate with a remote Unix machine whose address is given by address in the form of a (host, port) tuple. If address is not specified, ('localhost', 514) is used. The address is used to open a socket. An alternative to providing a (host, port) tuple is providing an address as a string, for example ‘/dev/log’. In this case, a Unix domain socket is used to send the message to the syslog. If facility is not specified, LOG_USER is used. The type of socket opened depends on the socktype argument, which defaults to socket.SOCK_DGRAM and thus opens a UDP socket. To open a TCP socket (for use with the newer syslog daemons such as rsyslog), specify a value of socket.SOCK_STREAM.
Note that if your server is not listening on UDP port 514, SysLogHandler may appear not to work. In that case, check what address you should be using for a domain socket - it’s system dependent. For example, on Linux it’s usually ‘/dev/log’ but on OS/X it’s ‘/var/run/syslog’. You’ll need to check your platform and use the appropriate address (you may need to do this check at runtime if your application needs to run on several platforms). On Windows, you pretty much have to use the UDP option.
Changed in version 3.2: socktype was added.
Closes the socket to the remote host.
The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.
Changed in version 3.2.1: (See: bpo-12168.) In earlier versions, the message sent to the syslog daemons was always terminated with a NUL byte, because early versions of these daemons expected a NUL terminated message - even though it’s not in the relevant specification (RFC 5424). More recent versions of these daemons don’t expect the NUL byte but strip it off if it’s there, and even more recent daemons (which adhere more closely to RFC 5424) pass the NUL byte on as part of the message.
To enable easier handling of syslog messages in the face of all these differing daemon behaviours, the appending of the NUL byte has been made configurable, through the use of a class-level attribute, append_nul. This defaults to True (preserving the existing behaviour) but can be set to False on a SysLogHandler instance in order for that instance to not append the NUL terminator.
Changed in version 3.3: (See: bpo-12419.) In earlier versions, there was no facility for an “ident” or “tag” prefix to identify the source of the message. This can now be specified using a class-level attribute, defaulting to "" to preserve existing behaviour, but which can be overridden on a SysLogHandler instance in order for that instance to prepend the ident to every message handled. Note that the provided ident must be text, not bytes, and is prepended to the message exactly as is.
Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.
The symbolic LOG_ values are defined in SysLogHandler and mirror the values defined in the sys/syslog.h header file.
Priorities
Name (string)
Symbolic value
alert
LOG_ALERT
crit or critical
LOG_CRIT
debug
LOG_DEBUG
emerg or panic
LOG_EMERG
err or error
LOG_ERR
info
LOG_INFO
notice
LOG_NOTICE
warn or warning
LOG_WARNING
Facilities
Name (string)
Symbolic value
auth
LOG_AUTH
authpriv
LOG_AUTHPRIV
cron
LOG_CRON
daemon
LOG_DAEMON
ftp
LOG_FTP
kern
LOG_KERN
lpr
LOG_LPR
mail
LOG_MAIL
news
LOG_NEWS
syslog
LOG_SYSLOG
user
LOG_USER
uucp
LOG_UUCP
local0
LOG_LOCAL0
local1
LOG_LOCAL1
local2
LOG_LOCAL2
local3
LOG_LOCAL3
local4
LOG_LOCAL4
local5
LOG_LOCAL5
local6
LOG_LOCAL6
local7
LOG_LOCAL7
Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps DEBUG, INFO, WARNING, ERROR and CRITICAL to the equivalent syslog names, and all other level names to ‘warning’.
The NTEventLogHandler class, located in the logging.handlers module, supports sending logging messages to a local Windows NT, Windows 2000 or Windows XP event log. Before you can use it, you need Mark Hammond’s Win32 extensions for Python installed.
Returns a new instance of the NTEventLogHandler class. The appname is used to define the application name as it appears in the event log. An appropriate registry entry is created using this name. The dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, 'win32service.pyd' is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own .dll or .exe which contains the message definitions you want to use in the event log). The logtype is one of 'Application', 'System' or 'Security', and defaults to 'Application'.
At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.
Determines the message ID, event category and event type, and then logs the message in the NT event log.
Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.
Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler’s typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler’s typemap attribute.
Returns the message ID for the record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32service.pyd.
The SMTPHandler class, located in the logging.handlers module, supports sending logging messages to an email address via SMTP.
Returns a new instance of the SMTPHandler class. The instance is initialized with the from and to addresses and subject line of the email. The toaddrs should be a list of strings. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. If you use a string, the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the credentials argument.
To specify the use of a secure protocol (TLS), pass in a tuple to the secure argument. This will only be used when authentication credentials are supplied. The tuple should be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the smtplib.SMTP.starttls() method.)
A timeout can be specified for communication with the SMTP server using the timeout argument.
New in version 3.3: The timeout argument was added.
Formats the record and sends it to the specified addressees.
If you want to specify a subject line which is record-dependent, override this method.
The MemoryHandler class, located in the logging.handlers module, supports buffering of logging records in memory, periodically flushing them to a target handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen.
MemoryHandler is a subclass of the more general BufferingHandler, which is an abstract class. This buffers logging records in memory. Whenever each record is added to the buffer, a check is made by calling shouldFlush() to see if the buffer should be flushed. If it should, then flush() is expected to do the flushing.
Initializes the handler with a buffer of the specified capacity. Here, capacity means the number of logging records buffered.
Append the record to the buffer. If shouldFlush() returns true, call flush() to process the buffer.
You can override this to implement custom flushing behavior. This version just zaps the buffer to empty.
Return True if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.
Returns a new instance of the MemoryHandler class. The instance is initialized with a buffer size of capacity (number of records buffered). If flushLevel is not specified, ERROR is used. If no target is specified, the target will need to be set using setTarget() before this handler does anything useful. If flushOnClose is specified as False, then the buffer is not flushed when the handler is closed. If not specified or specified as True, the previous behaviour of flushing the buffer will occur when the handler is closed.
Changed in version 3.6: The flushOnClose parameter was added.
Calls flush(), sets the target to None and clears the buffer.
For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. The buffer is also cleared when this happens. Override if you want different behavior.
Sets the target handler for this handler.
Checks for buffer full or a record at the flushLevel or higher.
The HTTPHandler class, located in the logging.handlers module, supports sending logging messages to a Web server, using either GET or POST semantics.
Returns a new instance of the HTTPHandler class. The host can be of the form host:port, should you need to use a specific port number. If no method is specified, GET is used. If secure is true, a HTTPS connection will be used. The context parameter may be set to a ssl.SSLContext instance to configure the SSL settings used for the HTTPS connection. If credentials is specified, it should be a 2-tuple consisting of userid and password, which will be placed in a HTTP ‘Authorization’ header using Basic authentication. If you specify credentials, you should also specify secure=True so that your userid and password are not passed in cleartext across the wire.
Changed in version 3.5: The context parameter was added.
Provides a dictionary, based on record, which is to be URL-encoded and sent to the web server. The default implementation just returns record.__dict__. This method can be overridden if e.g. only a subset of LogRecord is to be sent to the web server, or if more specific customization of what’s sent to the server is required.
Sends the record to the Web server as a URL-encoded dictionary. The mapLogRecord() method is used to convert the record to the dictionary to be sent.
Note
Since preparing a record for sending it to a Web server is not the same as a generic formatting operation, using setFormatter() to specify a Formatter for a HTTPHandler has no effect. Instead of calling format(), this handler calls mapLogRecord() and then urllib.parse.urlencode() to encode the dictionary in a form suitable for sending to a Web server.
New in version 3.2.
The QueueHandler class, located in the logging.handlers module, supports sending logging messages to a queue, such as those implemented in the queue or multiprocessing modules.
Along with the QueueListener class, QueueHandler can be used to let handlers do their work on a separate thread from the one which does the logging. This is important in Web applications and also other service applications where threads servicing clients need to respond as quickly as possible, while any potentially slow operations (such as sending an email via SMTPHandler) are done on a separate thread.
Returns a new instance of the QueueHandler class. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it’s used as-is by the enqueue() method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can use SimpleQueue instances for queue.
Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the handleError() method is called to handle the error. This can result in the record silently being dropped (if logging.raiseExceptions is False) or a message printed to sys.stderr (if logging.raiseExceptions is True).
Prepares a record for queuing. The object returned by this method is enqueued.
The base implementation formats the record to merge the message, arguments, and exception information, if present. It also removes unpickleable items from the record in-place.
You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.
Enqueues the record on the queue using put_nowait(); you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation.
New in version 3.2.
The QueueListener class, located in the logging.handlers module, supports receiving logging messages from a queue, such as those implemented in the queue or multiprocessing modules. The messages are received from a queue in an internal thread and passed, on the same thread, to one or more handlers for processing. While QueueListener is not itself a handler, it is documented here because it works hand-in-hand with QueueHandler.
Along with the QueueHandler class, QueueListener can be used to let handlers do their work on a separate thread from the one which does the logging. This is important in Web applications and also other service applications where threads servicing clients need to respond as quickly as possible, while any potentially slow operations (such as sending an email via SMTPHandler) are done on a separate thread.
Returns a new instance of the QueueListener class. The instance is initialized with the queue to send messages to and a list of handlers which will handle entries placed on the queue. The queue can be any queue-like object; it’s passed as-is to the dequeue() method, which needs to know how to get messages from it. The queue is not required to have the task tracking API (though it’s used if available), which means that you can use SimpleQueue instances for queue.
If respect_handler_level is True, a handler’s level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.
Changed in version 3.5: The respect_handler_level argument was added.
Dequeues a record and return it, optionally blocking.
The base implementation uses get(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
Prepare a record for handling.
This implementation just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers.
Handle a record.
This just loops through the handlers offering them the record to handle. The actual object passed to the handlers is that which is returned from prepare().
Starts the listener.
This starts up a background thread to monitor the queue for LogRecords to process.
Stops the listener.
This asks the thread to terminate, and then waits for it to do so. Note that if you don’t call this before your application exits, there may be some records still left on the queue, which won’t be processed.
Writes a sentinel to the queue to tell the listener to quit. This implementation uses put_nowait(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
New in version 3.3.
See also
API reference for the logging module.
Configuration API for the logging module.


The parameters are as for FileHandler. The attributes are:
If this attribute is set to a callable, the rotation_filename() method delegates to this callable. The parameters passed to the callable are those passed to rotation_filename().
Note
The namer function is called quite a few times during rollover, so it should be as simple and as fast as possible. It should also return the same output every time for a given input, otherwise the rollover behaviour may not work as expected.
New in version 3.3.
If this attribute is set to a callable, the rotate() method delegates to this callable. The parameters passed to the callable are those passed to rotate().
New in version 3.3.
Modify the filename of a log file when rotating.
This is provided so that a custom filename can be provided.
The default implementation calls the ‘namer’ attribute of the handler, if it’s callable, passing the default name to it. If the attribute isn’t callable (the default is None), the name is returned unchanged.
default_name – The default name for the log file.
New in version 3.3.
When rotating, rotate the current log.
The default implementation calls the ‘rotator’ attribute of the handler, if it’s callable, passing the source and dest arguments to it. If the attribute isn’t callable (the default is None), the source is simply renamed to the destination.
New in version 3.3.


If this attribute is set to a callable, the rotation_filename() method delegates to this callable. The parameters passed to the callable are those passed to rotation_filename().
Note
The namer function is called quite a few times during rollover, so it should be as simple and as fast as possible. It should also return the same output every time for a given input, otherwise the rollover behaviour may not work as expected.
New in version 3.3.


When rotating, rotate the current log.
The default implementation calls the ‘rotator’ attribute of the handler, if it’s callable, passing the source and dest arguments to it. If the attribute isn’t callable (the default is None), the source is simply renamed to the destination.
New in version 3.3.


Modify the filename of a log file when rotating.
This is provided so that a custom filename can be provided.
The default implementation calls the ‘namer’ attribute of the handler, if it’s callable, passing the default name to it. If the attribute isn’t callable (the default is None), the name is returned unchanged.
default_name – The default name for the log file.
New in version 3.3.


If this attribute is set to a callable, the rotate() method delegates to this callable. The parameters passed to the callable are those passed to rotate().
New in version 3.3.


Initializes the handler with a buffer of the specified capacity. Here, capacity means the number of logging records buffered.
Append the record to the buffer. If shouldFlush() returns true, call flush() to process the buffer.
You can override this to implement custom flushing behavior. This version just zaps the buffer to empty.
Return True if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.


Append the record to the buffer. If shouldFlush() returns true, call flush() to process the buffer.


You can override this to implement custom flushing behavior. This version just zaps the buffer to empty.


Return True if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.


Returns a new instance of the DatagramHandler class intended to communicate with a remote machine whose address is given by host and port.
Changed in version 3.4: If port is specified as None, a Unix domain socket is created using the value in host - otherwise, a UDP socket is created.
Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.
The factory method of SocketHandler is here overridden to create a UDP socket (socket.SOCK_DGRAM).
Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for SocketHandler.makePickle().


Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.


The factory method of SocketHandler is here overridden to create a UDP socket (socket.SOCK_DGRAM).


Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for SocketHandler.makePickle().


Returns a new instance of the HTTPHandler class. The host can be of the form host:port, should you need to use a specific port number. If no method is specified, GET is used. If secure is true, a HTTPS connection will be used. The context parameter may be set to a ssl.SSLContext instance to configure the SSL settings used for the HTTPS connection. If credentials is specified, it should be a 2-tuple consisting of userid and password, which will be placed in a HTTP ‘Authorization’ header using Basic authentication. If you specify credentials, you should also specify secure=True so that your userid and password are not passed in cleartext across the wire.
Changed in version 3.5: The context parameter was added.
Provides a dictionary, based on record, which is to be URL-encoded and sent to the web server. The default implementation just returns record.__dict__. This method can be overridden if e.g. only a subset of LogRecord is to be sent to the web server, or if more specific customization of what’s sent to the server is required.
Sends the record to the Web server as a URL-encoded dictionary. The mapLogRecord() method is used to convert the record to the dictionary to be sent.
Note
Since preparing a record for sending it to a Web server is not the same as a generic formatting operation, using setFormatter() to specify a Formatter for a HTTPHandler has no effect. Instead of calling format(), this handler calls mapLogRecord() and then urllib.parse.urlencode() to encode the dictionary in a form suitable for sending to a Web server.


Sends the record to the Web server as a URL-encoded dictionary. The mapLogRecord() method is used to convert the record to the dictionary to be sent.


Provides a dictionary, based on record, which is to be URL-encoded and sent to the web server. The default implementation just returns record.__dict__. This method can be overridden if e.g. only a subset of LogRecord is to be sent to the web server, or if more specific customization of what’s sent to the server is required.


Returns a new instance of the MemoryHandler class. The instance is initialized with a buffer size of capacity (number of records buffered). If flushLevel is not specified, ERROR is used. If no target is specified, the target will need to be set using setTarget() before this handler does anything useful. If flushOnClose is specified as False, then the buffer is not flushed when the handler is closed. If not specified or specified as True, the previous behaviour of flushing the buffer will occur when the handler is closed.
Changed in version 3.6: The flushOnClose parameter was added.
Calls flush(), sets the target to None and clears the buffer.
For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. The buffer is also cleared when this happens. Override if you want different behavior.
Sets the target handler for this handler.
Checks for buffer full or a record at the flushLevel or higher.


Calls flush(), sets the target to None and clears the buffer.


For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. The buffer is also cleared when this happens. Override if you want different behavior.


Sets the target handler for this handler.


Checks for buffer full or a record at the flushLevel or higher.


Returns a new instance of the NTEventLogHandler class. The appname is used to define the application name as it appears in the event log. An appropriate registry entry is created using this name. The dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, 'win32service.pyd' is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own .dll or .exe which contains the message definitions you want to use in the event log). The logtype is one of 'Application', 'System' or 'Security', and defaults to 'Application'.
At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.
Determines the message ID, event category and event type, and then logs the message in the NT event log.
Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.
Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler’s typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler’s typemap attribute.
Returns the message ID for the record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32service.pyd.


At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.


Determines the message ID, event category and event type, and then logs the message in the NT event log.


Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.


Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler’s typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler’s typemap attribute.


Returns the message ID for the record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32service.pyd.


Returns a new instance of the QueueHandler class. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it’s used as-is by the enqueue() method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can use SimpleQueue instances for queue.
Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the handleError() method is called to handle the error. This can result in the record silently being dropped (if logging.raiseExceptions is False) or a message printed to sys.stderr (if logging.raiseExceptions is True).
Prepares a record for queuing. The object returned by this method is enqueued.
The base implementation formats the record to merge the message, arguments, and exception information, if present. It also removes unpickleable items from the record in-place.
You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.
Enqueues the record on the queue using put_nowait(); you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation.


Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the handleError() method is called to handle the error. This can result in the record silently being dropped (if logging.raiseExceptions is False) or a message printed to sys.stderr (if logging.raiseExceptions is True).


Enqueues the record on the queue using put_nowait(); you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation.


Prepares a record for queuing. The object returned by this method is enqueued.
The base implementation formats the record to merge the message, arguments, and exception information, if present. It also removes unpickleable items from the record in-place.
You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.


Returns a new instance of the QueueListener class. The instance is initialized with the queue to send messages to and a list of handlers which will handle entries placed on the queue. The queue can be any queue-like object; it’s passed as-is to the dequeue() method, which needs to know how to get messages from it. The queue is not required to have the task tracking API (though it’s used if available), which means that you can use SimpleQueue instances for queue.
If respect_handler_level is True, a handler’s level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.
Changed in version 3.5: The respect_handler_level argument was added.
Dequeues a record and return it, optionally blocking.
The base implementation uses get(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
Prepare a record for handling.
This implementation just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers.
Handle a record.
This just loops through the handlers offering them the record to handle. The actual object passed to the handlers is that which is returned from prepare().
Starts the listener.
This starts up a background thread to monitor the queue for LogRecords to process.
Stops the listener.
This asks the thread to terminate, and then waits for it to do so. Note that if you don’t call this before your application exits, there may be some records still left on the queue, which won’t be processed.
Writes a sentinel to the queue to tell the listener to quit. This implementation uses put_nowait(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
New in version 3.3.


Dequeues a record and return it, optionally blocking.
The base implementation uses get(). You may want to override this method if you want to use timeouts or work with custom queue implementations.


Writes a sentinel to the queue to tell the listener to quit. This implementation uses put_nowait(). You may want to override this method if you want to use timeouts or work with custom queue implementations.
New in version 3.3.


Handle a record.
This just loops through the handlers offering them the record to handle. The actual object passed to the handlers is that which is returned from prepare().


Prepare a record for handling.
This implementation just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers.


Starts the listener.
This starts up a background thread to monitor the queue for LogRecords to process.


Stops the listener.
This asks the thread to terminate, and then waits for it to do so. Note that if you don’t call this before your application exits, there may be some records still left on the queue, which won’t be processed.


Returns a new instance of the RotatingFileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is provided, it determines how encoding errors are handled.
You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length; but if either of maxBytes or backupCount is zero, rollover never occurs, so you generally want to set backupCount to at least 1, and have a non-zero maxBytes. When backupCount is non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., to the filename. For example, with a backupCount of 5 and a base file name of app.log, you would get app.log, app.log.1, app.log.2, up to app.log.5. The file being written to is always app.log. When this file is filled, it is closed and renamed to app.log.1, and if files app.log.1, app.log.2, etc. exist, then they are renamed to app.log.2, app.log.3 etc. respectively.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Does a rollover, as described above.
Outputs the record to the file, catering for rollover as described previously.


Outputs the record to the file, catering for rollover as described previously.


Returns a new instance of the SMTPHandler class. The instance is initialized with the from and to addresses and subject line of the email. The toaddrs should be a list of strings. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. If you use a string, the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the credentials argument.
To specify the use of a secure protocol (TLS), pass in a tuple to the secure argument. This will only be used when authentication credentials are supplied. The tuple should be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the smtplib.SMTP.starttls() method.)
A timeout can be specified for communication with the SMTP server using the timeout argument.
New in version 3.3: The timeout argument was added.
Formats the record and sends it to the specified addressees.
If you want to specify a subject line which is record-dependent, override this method.


Formats the record and sends it to the specified addressees.


If you want to specify a subject line which is record-dependent, override this method.


Returns a new instance of the SocketHandler class intended to communicate with a remote machine whose address is given by host and port.
Changed in version 3.4: If port is specified as None, a Unix domain socket is created using the value in host - otherwise, a TCP socket is created.
Closes the socket.
Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. If the connection was previously lost, re-establishes the connection. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.
Handles an error which has occurred during emit(). The most likely cause is a lost connection. Closes the socket so that we can retry on the next event.
This is a factory method which allows subclasses to define the precise type of socket they want. The default implementation creates a TCP socket (socket.SOCK_STREAM).
Pickles the record’s attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket. The details of this operation are equivalent to:
Note that pickles aren’t completely secure. If you are concerned about security, you may want to override this method to implement a more secure mechanism. For example, you can sign pickles using HMAC and then verify them on the receiving end, or alternatively you can disable unpickling of global objects on the receiving end.
Send a pickled byte-string packet to the socket. The format of the sent byte-string is as described in the documentation for makePickle().
This function allows for partial sends, which can happen when the network is busy.
Tries to create a socket; on failure, uses an exponential back-off algorithm. On initial failure, the handler will drop the message it was trying to send. When subsequent messages are handled by the same instance, it will not try connecting until some time has passed. The default parameters are such that the initial delay is one second, and if after that delay the connection still can’t be made, the handler will double the delay each time up to a maximum of 30 seconds.
This behaviour is controlled by the following handler attributes:
This means that if the remote listener starts up after the handler has been used, you could lose messages (since the handler won’t even attempt a connection until the delay has elapsed, but just silently drop messages during the delay period).


Tries to create a socket; on failure, uses an exponential back-off algorithm. On initial failure, the handler will drop the message it was trying to send. When subsequent messages are handled by the same instance, it will not try connecting until some time has passed. The default parameters are such that the initial delay is one second, and if after that delay the connection still can’t be made, the handler will double the delay each time up to a maximum of 30 seconds.
This behaviour is controlled by the following handler attributes:
This means that if the remote listener starts up after the handler has been used, you could lose messages (since the handler won’t even attempt a connection until the delay has elapsed, but just silently drop messages during the delay period).


Pickles the record’s attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. If the connection was previously lost, re-establishes the connection. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord() function.


Handles an error which has occurred during emit(). The most likely cause is a lost connection. Closes the socket so that we can retry on the next event.


Pickles the record’s attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket. The details of this operation are equivalent to:
Note that pickles aren’t completely secure. If you are concerned about security, you may want to override this method to implement a more secure mechanism. For example, you can sign pickles using HMAC and then verify them on the receiving end, or alternatively you can disable unpickling of global objects on the receiving end.


This is a factory method which allows subclasses to define the precise type of socket they want. The default implementation creates a TCP socket (socket.SOCK_STREAM).


Send a pickled byte-string packet to the socket. The format of the sent byte-string is as described in the documentation for makePickle().
This function allows for partial sends, which can happen when the network is busy.


Returns a new instance of the SysLogHandler class intended to communicate with a remote Unix machine whose address is given by address in the form of a (host, port) tuple. If address is not specified, ('localhost', 514) is used. The address is used to open a socket. An alternative to providing a (host, port) tuple is providing an address as a string, for example ‘/dev/log’. In this case, a Unix domain socket is used to send the message to the syslog. If facility is not specified, LOG_USER is used. The type of socket opened depends on the socktype argument, which defaults to socket.SOCK_DGRAM and thus opens a UDP socket. To open a TCP socket (for use with the newer syslog daemons such as rsyslog), specify a value of socket.SOCK_STREAM.
Note that if your server is not listening on UDP port 514, SysLogHandler may appear not to work. In that case, check what address you should be using for a domain socket - it’s system dependent. For example, on Linux it’s usually ‘/dev/log’ but on OS/X it’s ‘/var/run/syslog’. You’ll need to check your platform and use the appropriate address (you may need to do this check at runtime if your application needs to run on several platforms). On Windows, you pretty much have to use the UDP option.
Changed in version 3.2: socktype was added.
Closes the socket to the remote host.
The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.
Changed in version 3.2.1: (See: bpo-12168.) In earlier versions, the message sent to the syslog daemons was always terminated with a NUL byte, because early versions of these daemons expected a NUL terminated message - even though it’s not in the relevant specification (RFC 5424). More recent versions of these daemons don’t expect the NUL byte but strip it off if it’s there, and even more recent daemons (which adhere more closely to RFC 5424) pass the NUL byte on as part of the message.
To enable easier handling of syslog messages in the face of all these differing daemon behaviours, the appending of the NUL byte has been made configurable, through the use of a class-level attribute, append_nul. This defaults to True (preserving the existing behaviour) but can be set to False on a SysLogHandler instance in order for that instance to not append the NUL terminator.
Changed in version 3.3: (See: bpo-12419.) In earlier versions, there was no facility for an “ident” or “tag” prefix to identify the source of the message. This can now be specified using a class-level attribute, defaulting to "" to preserve existing behaviour, but which can be overridden on a SysLogHandler instance in order for that instance to prepend the ident to every message handled. Note that the provided ident must be text, not bytes, and is prepended to the message exactly as is.
Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.
The symbolic LOG_ values are defined in SysLogHandler and mirror the values defined in the sys/syslog.h header file.
Priorities
Name (string)
Symbolic value
alert
LOG_ALERT
crit or critical
LOG_CRIT
debug
LOG_DEBUG
emerg or panic
LOG_EMERG
err or error
LOG_ERR
info
LOG_INFO
notice
LOG_NOTICE
warn or warning
LOG_WARNING
Facilities
Name (string)
Symbolic value
auth
LOG_AUTH
authpriv
LOG_AUTHPRIV
cron
LOG_CRON
daemon
LOG_DAEMON
ftp
LOG_FTP
kern
LOG_KERN
lpr
LOG_LPR
mail
LOG_MAIL
news
LOG_NEWS
syslog
LOG_SYSLOG
user
LOG_USER
uucp
LOG_UUCP
local0
LOG_LOCAL0
local1
LOG_LOCAL1
local2
LOG_LOCAL2
local3
LOG_LOCAL3
local4
LOG_LOCAL4
local5
LOG_LOCAL5
local6
LOG_LOCAL6
local7
LOG_LOCAL7
Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps DEBUG, INFO, WARNING, ERROR and CRITICAL to the equivalent syslog names, and all other level names to ‘warning’.


The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.
Changed in version 3.2.1: (See: bpo-12168.) In earlier versions, the message sent to the syslog daemons was always terminated with a NUL byte, because early versions of these daemons expected a NUL terminated message - even though it’s not in the relevant specification (RFC 5424). More recent versions of these daemons don’t expect the NUL byte but strip it off if it’s there, and even more recent daemons (which adhere more closely to RFC 5424) pass the NUL byte on as part of the message.
To enable easier handling of syslog messages in the face of all these differing daemon behaviours, the appending of the NUL byte has been made configurable, through the use of a class-level attribute, append_nul. This defaults to True (preserving the existing behaviour) but can be set to False on a SysLogHandler instance in order for that instance to not append the NUL terminator.
Changed in version 3.3: (See: bpo-12419.) In earlier versions, there was no facility for an “ident” or “tag” prefix to identify the source of the message. This can now be specified using a class-level attribute, defaulting to "" to preserve existing behaviour, but which can be overridden on a SysLogHandler instance in order for that instance to prepend the ident to every message handled. Note that the provided ident must be text, not bytes, and is prepended to the message exactly as is.


Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.
The symbolic LOG_ values are defined in SysLogHandler and mirror the values defined in the sys/syslog.h header file.
Priorities
Name (string)
Symbolic value
alert
LOG_ALERT
crit or critical
LOG_CRIT
debug
LOG_DEBUG
emerg or panic
LOG_EMERG
err or error
LOG_ERR
info
LOG_INFO
notice
LOG_NOTICE
warn or warning
LOG_WARNING
Facilities
Name (string)
Symbolic value
auth
LOG_AUTH
authpriv
LOG_AUTHPRIV
cron
LOG_CRON
daemon
LOG_DAEMON
ftp
LOG_FTP
kern
LOG_KERN
lpr
LOG_LPR
mail
LOG_MAIL
news
LOG_NEWS
syslog
LOG_SYSLOG
user
LOG_USER
uucp
LOG_UUCP
local0
LOG_LOCAL0
local1
LOG_LOCAL1
local2
LOG_LOCAL2
local3
LOG_LOCAL3
local4
LOG_LOCAL4
local5
LOG_LOCAL5
local6
LOG_LOCAL6
local7
LOG_LOCAL7


Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps DEBUG, INFO, WARNING, ERROR and CRITICAL to the equivalent syslog names, and all other level names to ‘warning’.


Returns a new instance of the TimedRotatingFileHandler class. The specified file is opened and used as the stream for logging. On rotating it also sets the filename suffix. Rotating happens based on the product of when and interval.
You can use the when to specify the type of interval. The list of possible values is below. Note that they are not case sensitive.
Value
Type of interval
If/how atTime is used
'S'
Seconds
Ignored
'M'
Minutes
Ignored
'H'
Hours
Ignored
'D'
Days
Ignored
'W0'-'W6'
Weekday (0=Monday)
Used to compute initial rollover time
'midnight'
Roll over at midnight, if atTime not specified, else at time atTime
Used to compute initial rollover time
When using weekday-based rotation, specify ‘W0’ for Monday, ‘W1’ for Tuesday, and so on up to ‘W6’ for Sunday. In this case, the value passed for interval isn’t used.
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.
When computing the next rollover time for the first time (when the handler is created), the last modification time of an existing log file, or else the current time, is used to compute when the next rotation will occur.
If the utc argument is true, times in UTC will be used; otherwise local time is used.
If backupCount is nonzero, at most backupCount files will be kept, and if more would be created when rollover occurs, the oldest one is deleted. The deletion logic uses the interval to determine which files to delete, so changing the interval may leave old files lying around.
If delay is true, then file opening is deferred until the first call to emit().
If atTime is not None, it must be a datetime.time instance which specifies the time of day when rollover occurs, for the cases where rollover is set to happen “at midnight” or “on a particular weekday”. Note that in these cases, the atTime value is effectively used to compute the initial rollover, and subsequent rollovers would be calculated via the normal interval calculation.
If errors is specified, it’s used to determine how encoding errors are handled.
Note
Calculation of the initial rollover time is done when the handler is initialised. Calculation of subsequent rollover times is done only when rollover occurs, and rollover occurs only when emitting output. If this is not kept in mind, it might lead to some confusion. For example, if an interval of “every minute” is set, that does not mean you will always see log files with times (in the filename) separated by a minute; if, during application execution, logging output is generated more frequently than once a minute, then you can expect to see log files with times separated by a minute. If, on the other hand, logging messages are only output once every five minutes (say), then there will be gaps in the file times corresponding to the minutes where no output (and hence no rollover) occurred.
Changed in version 3.4: atTime parameter was added.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Does a rollover, as described above.
Outputs the record to the file, catering for rollover as described above.


Outputs the record to the file, catering for rollover as described above.


Returns a new instance of the WatchedFileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely. If errors is provided, it determines how encoding errors are handled.
Changed in version 3.6: As well as string values, Path objects are also accepted for the filename argument.
Changed in version 3.9: The errors parameter was added.
Checks to see if the file has changed. If it has, the existing stream is flushed and closed and the file opened again, typically as a precursor to outputting the record to the file.
New in version 3.6.
Outputs the record to the file, but first calls reopenIfNeeded() to reopen the file if it has changed.


Outputs the record to the file, but first calls reopenIfNeeded() to reopen the file if it has changed.


Checks to see if the file has changed. If it has, the existing stream is flushed and closed and the file opened again, typically as a precursor to outputting the record to the file.
New in version 3.6.


Logs a message with level INFO on the root logger. The arguments are interpreted as for debug().


A “handler of last resort” is available through this attribute. This is a StreamHandler writing to sys.stderr with a level of WARNING, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to sys.stderr. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, lastResort can be set to None.
New in version 3.2.


Logs a message with level level on the root logger. The other arguments are interpreted as for debug().
Note
The above module-level convenience functions, which delegate to the root logger, call basicConfig() to ensure that at least one handler is available. Because of this, they should not be used in threads, in versions of Python earlier than 2.7.1 and 3.2, unless at least one handler has been added to the root logger before the threads are started. In earlier versions of Python, due to a thread safety shortcoming in basicConfig(), this can (under rare circumstances) lead to handlers being added multiple times to the root logger, which can in turn lead to multiple messages for the same event.


If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
The constructor sets this attribute to True.
Note
If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.
Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.
When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.
The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.
If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.
If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.
See Logging Levels for a list of levels.
Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO. Note, however, that levels are internally stored as integers, and methods such as e.g. getEffectiveLevel() and isEnabledFor() will return/expect to be passed integers.
Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by logging.disable(level) and then the logger’s effective level as determined by getEffectiveLevel().
Indicates the effective level for this logger. If a value other than NOTSET has been set using setLevel(), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than NOTSET is found, and that value is returned. The value returned is an integer, typically one of logging.DEBUG, logging.INFO etc.
Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, logging.getLogger('abc').getChild('def.ghi') would return the same logger as would be returned by logging.getLogger('abc.def.ghi'). This is a convenience method, useful when the parent logger is named using e.g. __name__ rather than a literal string.
New in version 3.2.
Logs a message with level DEBUG on this logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on msg when no args are supplied.
There are four keyword arguments in kwargs which are inspected: exc_info, stack_info, stacklevel and extra.
If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.
The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.
You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:
This mimics the Traceback (most recent call last): which is used when displaying exception frames.
The third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the warnings module.
The fourth keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:
would print something like
The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the Formatter documentation for more information on which keys are used by the logging system.)
If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the Formatter has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the extra dictionary with these keys.
While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers.
Changed in version 3.2: The stack_info parameter was added.
Changed in version 3.5: The exc_info parameter can now accept exception instances.
Changed in version 3.8: The stacklevel parameter was added.
Logs a message with level INFO on this logger. The arguments are interpreted as for debug().
Logs a message with level WARNING on this logger. The arguments are interpreted as for debug().
Note
There is an obsolete method warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.
Logs a message with level ERROR on this logger. The arguments are interpreted as for debug().
Logs a message with level CRITICAL on this logger. The arguments are interpreted as for debug().
Logs a message with integer level level on this logger. The other arguments are interpreted as for debug().
Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.
Adds the specified filter filter to this logger.
Removes the specified filter filter from this logger.
Apply this logger’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.
Adds the specified handler hdlr to this logger.
Removes the specified handler hdlr from this logger.
Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as None unless stack_info is True.
The stacklevel parameter is passed from code calling the debug() and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it.
Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of propagate is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using filter().
This is a factory method which can be overridden in subclasses to create specialized LogRecord instances.
Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns True if a handler was found, else False. The method stops searching up the hierarchy whenever a logger with the ‘propagate’ attribute set to false is found - that will be the last logger which is checked for the existence of handlers.
New in version 3.2.
Changed in version 3.7: Loggers can now be pickled and unpickled.


Adds the specified filter filter to this logger.


Adds the specified handler hdlr to this logger.


Logs a message with level CRITICAL on this logger. The arguments are interpreted as for debug().


Logs a message with level DEBUG on this logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on msg when no args are supplied.
There are four keyword arguments in kwargs which are inspected: exc_info, stack_info, stacklevel and extra.
If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.
The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.
You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:
This mimics the Traceback (most recent call last): which is used when displaying exception frames.
The third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the warnings module.
The fourth keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:
would print something like
The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the Formatter documentation for more information on which keys are used by the logging system.)
If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the Formatter has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the extra dictionary with these keys.
While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers.
Changed in version 3.2: The stack_info parameter was added.
Changed in version 3.5: The exc_info parameter can now accept exception instances.
Changed in version 3.8: The stacklevel parameter was added.


Logs a message with level ERROR on this logger. The arguments are interpreted as for debug().


Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.


Apply this logger’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.


Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as None unless stack_info is True.
The stacklevel parameter is passed from code calling the debug() and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it.


Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, logging.getLogger('abc').getChild('def.ghi') would return the same logger as would be returned by logging.getLogger('abc.def.ghi'). This is a convenience method, useful when the parent logger is named using e.g. __name__ rather than a literal string.
New in version 3.2.


Indicates the effective level for this logger. If a value other than NOTSET has been set using setLevel(), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than NOTSET is found, and that value is returned. The value returned is an integer, typically one of logging.DEBUG, logging.INFO etc.


Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of propagate is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using filter().


Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns True if a handler was found, else False. The method stops searching up the hierarchy whenever a logger with the ‘propagate’ attribute set to false is found - that will be the last logger which is checked for the existence of handlers.
New in version 3.2.


Logs a message with level INFO on this logger. The arguments are interpreted as for debug().


Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by logging.disable(level) and then the logger’s effective level as determined by getEffectiveLevel().


Logs a message with integer level level on this logger. The other arguments are interpreted as for debug().


This is a factory method which can be overridden in subclasses to create specialized LogRecord instances.


If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.
If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.
The constructor sets this attribute to True.
Note
If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.


Removes the specified filter filter from this logger.


Removes the specified handler hdlr from this logger.


Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.
When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.
The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.
If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.
If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.
See Logging Levels for a list of levels.
Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO. Note, however, that levels are internally stored as integers, and methods such as e.g. getEffectiveLevel() and isEnabledFor() will return/expect to be passed integers.


Logs a message with level WARNING on this logger. The arguments are interpreted as for debug().
Note
There is an obsolete method warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.


Returns an instance of LoggerAdapter initialized with an underlying Logger instance and a dict-like object.
Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as extra to the constructor and adds it to kwargs using key ‘extra’. The return value is a (msg, kwargs) tuple which has the (possibly modified) versions of the arguments passed in.


Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as extra to the constructor and adds it to kwargs using key ‘extra’. The return value is a (msg, kwargs) tuple which has the (possibly modified) versions of the arguments passed in.


Contains all the information pertinent to the event being logged.
The primary information is passed in msg and args, which are combined using msg % args to create the message field of the record.
Returns the message for this LogRecord instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, str() is called on it to convert it to a string. This allows use of user-defined classes as messages, whose __str__ method can return the actual format string to be used.
Changed in version 3.2: The creation of a LogRecord has been made more configurable by providing a factory which is used to create the record. The factory can be set using getLogRecordFactory() and setLogRecordFactory() (see this for the factory’s signature).
This functionality can be used to inject your own values into a LogRecord at creation time. You can use the following pattern:
With this pattern, multiple factories could be chained, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the standard attributes listed above, there should be no surprises.


Returns the message for this LogRecord instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, str() is called on it to convert it to a string. This allows use of user-defined classes as messages, whose __str__ method can return the actual format string to be used.


Creates and returns a new LogRecord instance whose attributes are defined by attrdict. This function is useful for taking a pickled LogRecord attribute dictionary, sent over a socket, and reconstituting it as a LogRecord instance at the receiving end.


Returns a new instance of the NullHandler class.
This method does nothing.
This method does nothing.
This method returns None for the lock, since there is no underlying I/O to which access needs to be serialized.


This method returns None for the lock, since there is no underlying I/O to which access needs to be serialized.


Tells the logging system to use the class klass when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__(). This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass: continue to use the logging.getLogger() API to get your loggers.


Set a callable which is used to create a LogRecord.
factory – The factory callable to be used to instantiate a log record.
New in version 3.2: This function has been provided, along with getLogRecordFactory(), to allow developers more control over how the LogRecord representing a logging event is constructed.
The factory has the following signature:
factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)
The logger name.
The logging level (numeric).
The full pathname of the file where the logging call was made.
The line number in the file where the logging call was made.
The logging message.
The arguments for the logging message.
An exception tuple, or None.
The name of the function or method which invoked the logging call.
A stack traceback such as is provided by traceback.print_stack(), showing the call hierarchy.
Additional keyword arguments.


Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call.
When the logging module is imported, it registers this function as an exit handler (see atexit), so normally there’s no need to do that manually.


Returns a new instance of the StreamHandler class. If stream is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.
If a formatter is specified, it is used to format the record. The record is then written to the stream followed by terminator. If exception information is present, it is formatted using traceback.print_exception() and appended to the stream.
Flushes the stream by calling its flush() method. Note that the close() method is inherited from Handler and so does no output, so an explicit flush() call may be needed at times.
Sets the instance’s stream to the specified value, if it is different. The old stream is flushed before the new stream is set.
stream – The stream that the handler should use.
the old stream, if the stream was changed, or None if it wasn’t.
New in version 3.7.
String used as the terminator when writing a formatted record to a stream. Default value is '\n'.
If you don’t want a newline termination, you can set the handler instance’s terminator attribute to the empty string.
In earlier versions, the terminator was hardcoded as '\n'.
New in version 3.2.


If a formatter is specified, it is used to format the record. The record is then written to the stream followed by terminator. If exception information is present, it is formatted using traceback.print_exception() and appended to the stream.


Flushes the stream by calling its flush() method. Note that the close() method is inherited from Handler and so does no output, so an explicit flush() call may be needed at times.


Sets the instance’s stream to the specified value, if it is different. The old stream is flushed before the new stream is set.
stream – The stream that the handler should use.
the old stream, if the stream was changed, or None if it wasn’t.
New in version 3.7.


String used as the terminator when writing a formatted record to a stream. Default value is '\n'.
If you don’t want a newline termination, you can set the handler instance’s terminator attribute to the empty string.
In earlier versions, the terminator was hardcoded as '\n'.
New in version 3.2.


Logs a message with level WARNING on the root logger. The arguments are interpreted as for debug().
Note
There is an obsolete function warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.


The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().