logging.handlers —- 日志处理
Important
此页面仅包含参考信息。有关教程,请参阅
The following useful handlers are provided in the package. Note that three ofthe handlers (StreamHandler
, FileHandler
andNullHandler
) are actually defined in the logging
module itself,but have been documented here along with the other handlers.
StreamHandler
The StreamHandler
class, located in the core logging
package,sends logging output to streams such as sys.stdout, sys.stderr or anyfile-like object (or, more precisely, any object which supports write()
and flush()
methods).
- class
logging.
StreamHandler
(stream=None) Returns a new instance of the
StreamHandler
class. If stream isspecified, the instance will use it for logging output; otherwise, _sys.stderr_will be used.emit
(record)If a formatter is specified, it is used to format the record. The recordis then written to the stream with a terminator. If exception informationis present, it is formatted using
traceback.print_exception()
andappended to the stream.Flushes the stream by calling its
flush()
method. Note that theclose()
method is inherited fromHandler
and sodoes no output, so an explicitflush()
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.
3.7 新版功能.
在 3.2 版更改: The StreamHandler
class now has a terminator
attribute, defaultvalue '\n'
, which is used as the terminator when writing a formattedrecord to a stream. If you don't want this newline termination, you canset the handler instance's terminator
attribute to the empty string.In earlier versions, the terminator was hardcoded as '\n'
.
FileHandler
The FileHandler
class, located in the core logging
package,sends logging output to a disk file. It inherits the output functionality fromStreamHandler
.
- class
logging.
FileHandler
(filename, mode='a', encoding=None, delay=False) - Returns a new instance of the
FileHandler
class. The specified file isopened and used as the stream for logging. If mode is not specified,'a'
is used. If encoding is notNone
, it is used to open the filewith that encoding. If delay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely.
在 3.6 版更改: As well as string values, Path
objects are also acceptedfor the filename argument.
NullHandler
3.1 新版功能.
The NullHandler
class, located in the core logging
package,does not do any formatting or output. It is essentially a 'no-op' handlerfor use by library developers.
- class
logging.
NullHandler
Returns a new instance of the
NullHandler
class.
See 配置库的日志记录 for more information on how to useNullHandler
.
WatchedFileHandler
The WatchedFileHandler
class, located in the logging.handlers
module, is a FileHandler
which watches the file it is logging to. Ifthe file changes, it is closed and reopened using the file name.
A file change can happen because of usage of programs such as newsyslog andlogrotate which perform log file rotation. This handler, intended for useunder 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 thefile has changed, the old file stream is closed, and the file opened to get anew stream.
This handler is not appropriate for use under Windows, because under Windowsopen log files cannot be moved or renamed - logging opens the files withexclusive locks - and so there is no need for such a handler. Furthermore,ST_INO is not supported under Windows; stat()
always returns zerofor this value.
- class
logging.handlers.
WatchedFileHandler
(filename, mode='a', encoding=None, delay=False) - Returns a new instance of the
WatchedFileHandler
class. The specifiedfile is opened and used as the stream for logging. If mode is not specified,'a'
is used. If encoding is notNone
, it is used to open the filewith that encoding. If delay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely.
在 3.6 版更改: As well as string values, Path
objects are also acceptedfor the filename argument.
reopenIfNeeded
()- Checks to see if the file has changed. If it has, the existing stream isflushed and closed and the file opened again, typically as a precursor tooutputting the record to the file.
3.6 新版功能.
emit
(record)- Outputs the record to the file, but first calls
reopenIfNeeded()
toreopen the file if it has changed.
BaseRotatingHandler
The BaseRotatingHandler
class, located in the logging.handlers
module, is the base class for the rotating file handlers,RotatingFileHandler
and TimedRotatingFileHandler
. You shouldnot need to instantiate this class, but it has attributes and methods you mayneed to override.
- class
logging.handlers.
BaseRotatingHandler
(filename, mode, encoding=None, delay=False) The parameters are as for
FileHandler
. The attributes are:namer
- If this attribute is set to a callable, the
rotation_filename()
method delegates to this callable. The parameters passed to the callableare those passed torotation_filename()
.
注解
The namer function is called quite a few times during rollover,so it should be as simple and as fast as possible. It should alsoreturn the same output every time for a given input, otherwise therollover behaviour may not work as expected.
3.3 新版功能.
rotator
- If this attribute is set to a callable, the
rotate()
methoddelegates to this callable. The parameters passed to the callable arethose passed torotate()
.
3.3 新版功能.
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'tcallable (the default is None
), the name is returned unchanged.
- 参数
-
default_name — The default name for the log file.
3.3 新版功能.
The default implementation calls the 'rotator' attribute of the handler,if it's callable, passing the source and dest arguments to it. If theattribute isn't callable (the default is None
), the source is simplyrenamed to the destination.
- 参数
-
-
source — The source filename. This is normally the basefilename, e.g. 'test.log'.
-
dest — The destination filename. This is normallywhat the source is rotated to, e.g. 'test.log.1'.
3.3 新版功能.
The reason the attributes exist is to save you having to subclass - you can usethe same callables for instances of RotatingFileHandler
andTimedRotatingFileHandler
. If either the namer or rotator callableraises an exception, this will be handled in the same way as any otherexception during an emit()
call, i.e. via the handleError()
methodof the handler.
If you need to make more significant changes to rotation processing, you canoverride the methods.
For an example, see Using a rotator and namer to customize log rotation processing.
RotatingFileHandler
The RotatingFileHandler
class, located in the logging.handlers
module, supports rotation of disk log files.
- class
logging.handlers.
RotatingFileHandler
(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False) - Returns a new instance of the
RotatingFileHandler
class. The specifiedfile is opened and used as the stream for logging. If mode is not specified,'a'
is used. If encoding is notNone
, it is used to open the filewith that encoding. If delay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely.
You can use the maxBytes and backupCount values to allow the file torollover 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 occurswhenever the current log file is nearly maxBytes in length; but if either ofmaxBytes or backupCount is zero, rollover never occurs, so you generally wantto 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 appendingthe 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 beingwritten to is always app.log
. When this file is filled, it is closedand 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.
在 3.6 版更改: As well as string values, Path
objects are also acceptedfor the filename argument.
doRollover
()Does a rollover, as described above.
- Outputs the record to the file, catering for rollover as describedpreviously.
TimedRotatingFileHandler
The TimedRotatingFileHandler
class, located in thelogging.handlers
module, supports rotation of disk log files at certaintimed intervals.
- class
logging.handlers.
TimedRotatingFileHandler
(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None) - Returns a new instance of the
TimedRotatingFileHandler
class. Thespecified file is opened and used as the stream for logging. On rotating it alsosets the filename suffix. Rotating happens based on the product of when andinterval.
You can use the when to specify the type of interval. The list of possiblevalues is below. Note that they are not case sensitive.
值
间隔类型
如果/如何使用 atTime
'S'
秒
忽略
'M'
分钟
忽略
'H'
小时
忽略
'D'
天
忽略
'W0'-'W6'
工作日(0=星期一)
Used to compute initialrollover time
'midnight'
Roll over at midnight, ifatTime not specified,else at time atTime
Used to compute initialrollover time
When using weekday-based rotation, specify 'W0' for Monday, 'W1' forTuesday, and so on up to 'W6' for Sunday. In this case, the value passed forinterval 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 therollover interval.
When computing the next rollover time for the first time (when the handleris created), the last modification time of an existing log file, or elsethe current time, is used to compute when the next rotation will occur.
If the utc argument is true, times in UTC will be used; otherwiselocal time is used.
If backupCount is nonzero, at most backupCount fileswill be kept, and if more would be created when rollover occurs, the oldestone is deleted. The deletion logic uses the interval to determine whichfiles 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 toemit()
.
If atTime is not None
, it must be a datetime.time
instance whichspecifies the time of day when rollover occurs, for the cases where rolloveris set to happen "at midnight" or "on a particular weekday". Note that inthese cases, the atTime value is effectively used to compute the _initial_rollover, and subsequent rollovers would be calculated via the normalinterval calculation.
注解
Calculation of the initial rollover time is done when the handleris initialised. Calculation of subsequent rollover times is done onlywhen rollover occurs, and rollover occurs only when emitting output. Ifthis 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 willalways see log files with times (in the filename) separated by a minute;if, during application execution, logging output is generated morefrequently than once a minute, then you can expect to see log fileswith times separated by a minute. If, on the other hand, logging messagesare only output once every five minutes (say), then there will be gaps inthe file times corresponding to the minutes where no output (and hence norollover) occurred.
在 3.4 版更改: atTime parameter was added.
在 3.6 版更改: As well as string values, Path
objects are also acceptedfor the filename argument.
doRollover
()Does a rollover, as described above.
- Outputs the record to the file, catering for rollover as described above.
SocketHandler
The SocketHandler
class, located in the logging.handlers
module,sends logging output to a network socket. The base class uses a TCP socket.
- class
logging.handlers.
SocketHandler
(host, port) - Returns a new instance of the
SocketHandler
class intended tocommunicate with a remote machine whose address is given by host and port.
在 3.4 版更改: If port
is specified as None
, a Unix domain socket is createdusing the value in host
- otherwise, a TCP socket is created.
close
()Closes the socket.
Pickles the record's attribute dictionary and writes it to the socket inbinary format. If there is an error with the socket, silently drops thepacket. If the connection was previously lost, re-establishes theconnection. To unpickle the record at the receiving end into a
LogRecord
, use themakeLogRecord()
function.Handles an error which has occurred during
emit()
. The most likelycause is a lost connection. Closes the socket so that we can retry on thenext event.This is a factory method which allows subclasses to define the precisetype 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 lengthprefix, and returns it ready for transmission across the socket. Thedetails of this operation are equivalent to:
- data = pickle.dumps(record_attr_dict, 1)
- datalen = struct.pack('>L', len(data))
- return datalen + data
Note that pickles aren't completely secure. If you are concerned aboutsecurity, you may want to override this method to implement a more securemechanism. For example, you can sign pickles using HMAC and then verifythem on the receiving end, or alternatively you can disable unpickling ofglobal objects on the receiving end.
send
(packet)- Send a pickled byte-string packet to the socket. The format of the sentbyte-string is as described in the documentation for
makePickle()
.
This function allows for partial sends, which can happen when the networkis busy.
createSocket
()- Tries to create a socket; on failure, uses an exponential back-offalgorithm. On initial failure, the handler will drop the message it wastrying to send. When subsequent messages are handled by the sameinstance, it will not try connecting until some time has passed. Thedefault parameters are such that the initial delay is one second, and ifafter that delay the connection still can't be made, the handler willdouble the delay each time up to a maximum of 30 seconds.
This behaviour is controlled by the following handler attributes:
-
retryStart
(initial delay, defaulting to 1.0 seconds).
-
retryFactor
(multiplier, defaulting to 2.0).
-
retryMax
(maximum delay, defaulting to 30.0 seconds).
This means that if the remote listener starts up after the handler hasbeen used, you could lose messages (since the handler won't even attempta connection until the delay has elapsed, but just silently drop messagesduring the delay period).
DatagramHandler
The DatagramHandler
class, located in the logging.handlers
module, inherits from SocketHandler
to support sending logging messagesover UDP sockets.
- class
logging.handlers.
DatagramHandler
(host, port) - Returns a new instance of the
DatagramHandler
class intended tocommunicate with a remote machine whose address is given by host and port.
在 3.4 版更改: If port
is specified as None
, a Unix domain socket is createdusing the value in host
- otherwise, a UDP socket is created.
emit
()Pickles the record's attribute dictionary and writes it to the socket inbinary format. If there is an error with the socket, silently drops thepacket. To unpickle the record at the receiving end into a
LogRecord
, use themakeLogRecord()
function.The factory method of
SocketHandler
is here overridden to createa UDP socket (socket.SOCK_DGRAM
).- Send a pickled byte-string to a socket. The format of the sent byte-stringis as described in the documentation for
SocketHandler.makePickle()
.
SysLogHandler
The SysLogHandler
class, located in the logging.handlers
module,supports sending logging messages to a remote or local Unix syslog.
- class
logging.handlers.
SysLogHandler
(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM) - Returns a new instance of the
SysLogHandler
class intended tocommunicate with a remote Unix machine whose address is given by address inthe form of a(host, port)
tuple. If address is not specified,('localhost', 514)
is used. The address is used to open a socket. Analternative to providing a(host, port)
tuple is providing an address as astring, for example '/dev/log'. In this case, a Unix domain socket is used tosend the message to the syslog. If facility is not specified,LOGUSER
is used. The type of socket opened depends on the_socktype argument, which defaults tosocket.SOCK_DGRAM
and thusopens a UDP socket. To open a TCP socket (for use with the newer syslogdaemons such as rsyslog), specify a value ofsocket.SOCK_STREAM
.
Note that if your server is not listening on UDP port 514,SysLogHandler
may appear not to work. In that case, check whataddress 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 theappropriate address (you may need to do this check at runtime if yourapplication needs to run on several platforms). On Windows, you prettymuch have to use the UDP option.
在 3.2 版更改: socktype was added.
close
()Closes the socket to the remote host.
- The record is formatted, and then sent to the syslog server. If exceptioninformation is present, it is not sent to the server.
在 3.2.1 版更改: (See: bpo-12168.) In earlier versions, the message sent to thesyslog daemons was always terminated with a NUL byte, because earlyversions of these daemons expected a NUL terminated message - eventhough it's not in the relevant specification (RFC 5424). More recentversions of these daemons don't expect the NUL byte but strip it offif it's there, and even more recent daemons (which adhere more closelyto RFC 5424) pass the NUL byte on as part of the message.
To enable easier handling of syslog messages in the face of all thesediffering daemon behaviours, the appending of the NUL byte has beenmade configurable, through the use of a class-level attribute,appendnul
. This defaults to True
(preserving the existingbehaviour) but can be set to False
on a SysLogHandler
instancein order for that instance to _not append the NUL terminator.
在 3.3 版更改: (See: bpo-12419.) In earlier versions, there was no facility foran "ident" or "tag" prefix to identify the source of the message. Thiscan now be specified using a class-level attribute, defaulting to""
to preserve existing behaviour, but which can be overridden ona SysLogHandler
instance in order for that instance to prependthe ident to every message handled. Note that the provided ident mustbe text, not bytes, and is prepended to the message exactly as is.
encodePriority
(facility, priority)- Encodes the facility and priority into an integer. You can pass in stringsor integers - if strings are passed, internal mapping dictionaries areused to convert them to integers.
The symbolic LOG_
values are defined in SysLogHandler
andmirror the values defined in the sys/syslog.h
header file.
优先级
名称(字符串)
符号值
alert
LOG_ALERT
crit
或 critical
LOG_CRIT
debug
LOG_DEBUG
emerg
或 panic
LOG_EMERG
err
或 error
LOG_ERR
info
LOG_INFO
notice
LOG_NOTICE
warn
或 warning
LOG_WARNING
设备
名称(字符串)
符号值
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
mapPriority
(levelname)- Maps a logging level name to a syslog priority name.You may need to override this if you are using custom levels, orif the default algorithm is not suitable for your needs. Thedefault algorithm maps
DEBUG
,INFO
,WARNING
,ERROR
andCRITICAL
to the equivalent syslog names, and all other levelnames to 'warning'.
NTEventLogHandler
The NTEventLogHandler
class, located in the logging.handlers
module, supports sending logging messages to a local Windows NT, Windows 2000 orWindows XP event log. Before you can use it, you need Mark Hammond's Win32extensions for Python installed.
- class
logging.handlers.
NTEventLogHandler
(appname, dllname=None, logtype='Application') Returns a new instance of the
NTEventLogHandler
class. The appname isused to define the application name as it appears in the event log. Anappropriate registry entry is created using this name. The dllname should givethe fully qualified pathname of a .dll or .exe which contains messagedefinitions to hold in the log (if not specified,'win32service.pyd'
is used- this is installed with the Win32 extensions and contains some basicplaceholder message definitions. Note that use of these placeholders will makeyour event logs big, as the entire message source is held in the log. If youwant slimmer logs, you have to pass in the name of your own .dll or .exe whichcontains the message definitions you want to use in the event log). Thelogtype is one of'Application'
,'System'
or'Security'
, anddefaults to'Application'
.close
()At this point, you can remove the application name from the registry as asource of event log entries. However, if you do this, you will not be ableto see the events as you intended in the Event Log Viewer - it needs to beable to access the registry to get the .dll name. The current version doesnot do this.
Determines the message ID, event category and event type, and then logsthe message in the NT event log.
Returns the event category for the record. Override this if you want tospecify your own categories. This version returns 0.
Returns the event type for the record. Override this if you want tospecify your own types. This version does a mapping using the handler'stypemap attribute, which is set up in
init()
to a dictionarywhich contains mappings forDEBUG
,INFO
,WARNING
,ERROR
andCRITICAL
. If you are usingyour own levels, you will either need to override this method or place asuitable 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 IDrather than a format string. Then, in here, you could use a dictionarylookup to get the message ID. This version returns 1, which is the basemessage ID in
win32service.pyd
.
SMTPHandler
The SMTPHandler
class, located in the logging.handlers
module,supports sending logging messages to an email address via SMTP.
- class
logging.handlers.
SMTPHandler
(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0) - Returns a new instance of the
SMTPHandler
class. The instance isinitialized with the from and to addresses and subject line of the email. Thetoaddrs should be a list of strings. To specify a non-standard SMTP port, usethe (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, youcan specify a (username, password) tuple for the credentials argument.
To specify the use of a secure protocol (TLS), pass in a tuple to thesecure argument. This will only be used when authentication credentials aresupplied. The tuple should be either an empty tuple, or a single-value tuplewith the name of a keyfile, or a 2-value tuple with the names of the keyfileand certificate file. (This tuple is passed to thesmtplib.SMTP.starttls()
method.)
A timeout can be specified for communication with the SMTP server using thetimeout argument.
3.3 新版功能: The timeout argument was added.
emit
(record)Formats the record and sends it to the specified addressees.
- If you want to specify a subject line which is record-dependent, overridethis method.
MemoryHandler
The MemoryHandler
class, located in the logging.handlers
module,supports buffering of logging records in memory, periodically flushing them to atarget handler. Flushing occurs whenever the buffer is full, or when anevent of a certain severity or greater is seen.
MemoryHandler
is a subclass of the more generalBufferingHandler
, which is an abstract class. This buffers loggingrecords in memory. Whenever each record is added to the buffer, a check is madeby calling shouldFlush()
to see if the buffer should be flushed. If itshould, then flush()
is expected to do the flushing.
- class
logging.handlers.
BufferingHandler
(capacity) Initializes the handler with a buffer of the specified capacity. Here,capacity means the number of logging records buffered.
emit
(record)Append the record to the buffer. If
shouldFlush()
returns true,callflush()
to process the buffer.You can override this to implement custom flushing behavior. This versionjust zaps the buffer to empty.
- Return
True
if the buffer is up to capacity. This method can beoverridden to implement custom flushing strategies.
class
logging.handlers.
MemoryHandler
(capacity, flushLevel=ERROR, target=None, flushOnClose=True)- Returns a new instance of the
MemoryHandler
class. The instance isinitialized with a buffer size of capacity (number of records buffered).If flushLevel is not specified,ERROR
is used. If no target isspecified, the target will need to be set usingsetTarget()
before thishandler does anything useful. If flushOnClose is specified asFalse
,then the buffer is not flushed when the handler is closed. If not specifiedor specified asTrue
, the previous behaviour of flushing the buffer willoccur when the handler is closed.
在 3.6 版更改: The flushOnClose parameter was added.
close
()Calls
flush()
, sets the target toNone
and clears thebuffer.For a
MemoryHandler
, flushing means just sending the bufferedrecords to the target, if there is one. The buffer is also cleared whenthis 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.
HTTPHandler
The HTTPHandler
class, located in the logging.handlers
module,supports sending logging messages to a Web server, using either GET
orPOST
semantics.
- class
logging.handlers.
HTTPHandler
(host, url, method='GET', secure=False, credentials=None, context=None) - Returns a new instance of the
HTTPHandler
class. The host can beof the formhost:port
, should you need to use a specific port number. Ifno method is specified,GET
is used. If secure is true, a HTTPSconnection will be used. The context parameter may be set to assl.SSLContext
instance to configure the SSL settings used for theHTTPS connection. If credentials is specified, it should be a 2-tupleconsisting of userid and password, which will be placed in a HTTP'Authorization' header using Basic authentication. If you specifycredentials, you should also specify secure=True so that your userid andpassword are not passed in cleartext across the wire.
在 3.5 版更改: The context parameter was added.
mapLogRecord
(record)Provides a dictionary, based on
record
, which is to be URL-encodedand sent to the web server. The default implementation just returnsrecord.dict
. This method can be overridden if e.g. only asubset ofLogRecord
is to be sent to the web server, orif 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 thedictionary to be sent.
注解
Since preparing a record for sending it to a Web server is notthe same as a generic formatting operation, usingsetFormatter()
to specify aFormatter
for a HTTPHandler
has no effect.Instead of calling format()
, this handler callsmapLogRecord()
and then urllib.parse.urlencode()
to encode thedictionary in a form suitable for sending to a Web server.
QueueHandler
3.2 新版功能.
The QueueHandler
class, located in the logging.handlers
module,supports sending logging messages to a queue, such as those implemented in thequeue
or multiprocessing
modules.
Along with the QueueListener
class, QueueHandler
can be usedto let handlers do their work on a separate thread from the one which does thelogging. This is important in Web applications and also other serviceapplications where threads servicing clients need to respond as quickly aspossible, while any potentially slow operations (such as sending an email viaSMTPHandler
) are done on a separate thread.
- class
logging.handlers.
QueueHandler
(queue) Returns a new instance of the
QueueHandler
class. The instance isinitialized with the queue to send messages to. The queue can be anyqueue-like object; it's used as-is by theenqueue()
method, whichneeds to know how to send messages to it. The queue is not required tohave the task tracking API, which means that you can useSimpleQueue
instances for queue.emit
(record)Enqueues the result of preparing the LogRecord. Should an exceptionoccur (e.g. because a bounded queue has filled up), the
handleError()
method is called to handle theerror. This can result in the record silently being dropped (iflogging.raiseExceptions
isFalse
) or a message printed tosys.stderr
(iflogging.raiseExceptions
isTrue
).- Prepares a record for queuing. The object returned by thismethod is enqueued.
The base implementation formats the record to merge the message,arguments, and exception information, if present. It alsoremoves unpickleable items from the record in-place.
You might want to override this method if you want to convertthe record to a dict or JSON string, or send a modified copyof the record while leaving the original intact.
enqueue
(record)- Enqueues the record on the queue using
put_nowait()
; you maywant to override this if you want to use blocking behaviour, or atimeout, or a customized queue implementation.
QueueListener
3.2 新版功能.
The QueueListener
class, located in the logging.handlers
module, supports receiving logging messages from a queue, such as thoseimplemented in the queue
or multiprocessing
modules. Themessages are received from a queue in an internal thread and passed, onthe same thread, to one or more handlers for processing. WhileQueueListener
is not itself a handler, it is documented herebecause it works hand-in-hand with QueueHandler
.
Along with the QueueHandler
class, QueueListener
can be usedto let handlers do their work on a separate thread from the one which does thelogging. This is important in Web applications and also other serviceapplications where threads servicing clients need to respond as quickly aspossible, while any potentially slow operations (such as sending an email viaSMTPHandler
) are done on a separate thread.
- class
logging.handlers.
QueueListener
(queue, *handlers, respect_handler_level=False) - Returns a new instance of the
QueueListener
class. The instance isinitialized with the queue to send messages to and a list of handlers whichwill handle entries placed on the queue. The queue can be any queue-likeobject; it's passed as-is to thedequeue()
method, which needsto know how to get messages from it. The queue is not required to have thetask tracking API (though it's used if available), which means that you canuseSimpleQueue
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 passmessages to that handler; otherwise, the behaviour is as in previous Pythonversions - to always pass each message to each handler.
在 3.5 版更改: The respect_handler_level
argument was added.
The base implementation uses get()
. You may want to override thismethod if you want to use timeouts or work with custom queueimplementations.
This implementation just returns the passed-in record. You may want tooverride this method if you need to do any custom marshalling ormanipulation of the record before passing it to the handlers.
This just loops through the handlers offering them the recordto handle. The actual object passed to the handlers is that whichis returned from prepare()
.
This starts up a background thread to monitor the queue forLogRecords to process.
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, theremay be some records still left on the queue, which won't be processed.
enqueue_sentinel
()- Writes a sentinel to the queue to tell the listener to quit. Thisimplementation uses
put_nowait()
. You may want to override thismethod if you want to use timeouts or work with custom queueimplementations.
3.3 新版功能.
参见
- 模块
logging
日志记录模块的 API 参考。
- 日志记录模块的配置 API 。