logging.handlers
--- 日誌紀錄處理器¶
Important
This page contains only reference information. For tutorials,please see
The following useful handlers are provided in the package. Note that three ofthe handlers (StreamHandler
,FileHandler
andNullHandler
) are actually defined in thelogging
module itself,but have been documented here along with the other handlers.
StreamHandler¶
TheStreamHandler
class, located in the corelogging
package,sends logging output to streams such assys.stdout,sys.stderr or anyfile-like object (or, more precisely, any object which supportswrite()
andflush()
methods).
- classlogging.StreamHandler(stream=None)¶
Returns a new instance of the
StreamHandler
class. Ifstream isspecified, the instance will use it for logging output; otherwise,sys.stderrwill be used.- emit(record)¶
If a formatter is specified, it is used to format the record. The recordis then written to the stream followed by
terminator
. If exception informationis present, it is formatted usingtraceback.print_exception()
andappended to the stream.
- flush()¶
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.
- setStream(stream)¶
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 版被加入.
- terminator¶
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'
.在 3.2 版被加入.
FileHandler¶
TheFileHandler
class, located in the corelogging
package,sends logging output to a disk file. It inherits the output functionality fromStreamHandler
.
- classlogging.FileHandler(filename,mode='a',encoding=None,delay=False,errors=None)¶
Returns a new instance of the
FileHandler
class. The specified file isopened and used as the stream for logging. Ifmode is not specified,'a'
is used. Ifencoding is notNone
, it is used to open the filewith that encoding. Ifdelay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely. Iferrors is specified, it's used to determine how encoding errors are handled.在 3.6 版的變更:As well as string values,
Path
objects are also acceptedfor thefilename argument.在 3.9 版的變更:新增errors 參數。
- close()¶
Closes the file.
NullHandler¶
在 3.1 版被加入.
TheNullHandler
class, located in the corelogging
package,does not do any formatting or output. It is essentially a 'no-op' handlerfor use by library developers.
- classlogging.NullHandler¶
Returns a new instance of the
NullHandler
class.- emit(record)¶
This method does nothing.
- handle(record)¶
This method does nothing.
- createLock()¶
This method returns
None
for the lock, since there is nounderlying I/O to which access needs to be serialized.
SeeConfiguring Logging for a Library for more information on how to useNullHandler
.
WatchedFileHandler¶
TheWatchedFileHandler
class, located in thelogging.handlers
module, is aFileHandler
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 asnewsyslog 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.
- classlogging.handlers.WatchedFileHandler(filename,mode='a',encoding=None,delay=False,errors=None)¶
Returns a new instance of the
WatchedFileHandler
class. The specifiedfile is opened and used as the stream for logging. Ifmode is not specified,'a'
is used. Ifencoding is notNone
, it is used to open the filewith that encoding. Ifdelay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely. Iferrors is provided, it determines how encoding errors are handled.在 3.6 版的變更:As well as string values,
Path
objects are also acceptedfor thefilename argument.在 3.9 版的變更:新增errors 參數。
- 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¶
TheBaseRotatingHandler
class, located in thelogging.handlers
module, is the base class for the rotating file handlers,RotatingFileHandler
andTimedRotatingFileHandler
. You shouldnot need to instantiate this class, but it has attributes and methods you mayneed to override.
- classlogging.handlers.BaseRotatingHandler(filename,mode,encoding=None,delay=False,errors=None)¶
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.
It's also worth noting that care should be taken when using a namer topreserve certain attributes in the filename which are used during rotation.For example,
RotatingFileHandler
expects to have a set of log fileswhose names contain successive integers, so that rotation works as expected,andTimedRotatingFileHandler
deletes old log files (based on thebackupCount
parameter passed to the handler's initializer) by determiningthe oldest files to delete. For this to happen, the filenames should besortable using the date/time portion of the filename, and a namer needs torespect this. (If a namer is wanted that doesn't respect this scheme, it willneed to be used in a subclass ofTimedRotatingFileHandler
whichoverrides thegetFilesToDelete()
method tofit in with the custom naming scheme.)在 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 版被加入.
- rotation_filename(default_name)¶
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'tcallable (the default is
None
), the name is returned unchanged.- 參數:
default_name -- The default name for the log file.
在 3.3 版被加入.
- rotate(source,dest)¶
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 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 ofRotatingFileHandler
andTimedRotatingFileHandler
. If either the namer or rotator callableraises an exception, this will be handled in the same way as any otherexception during anemit()
call, i.e. via thehandleError()
methodof the handler.
If you need to make more significant changes to rotation processing, you canoverride the methods.
For an example, seeUsing a rotator and namer to customize log rotation processing.
RotatingFileHandler¶
TheRotatingFileHandler
class, located in thelogging.handlers
module, supports rotation of disk log files.
- classlogging.handlers.RotatingFileHandler(filename,mode='a',maxBytes=0,backupCount=0,encoding=None,delay=False,errors=None)¶
Returns a new instance of the
RotatingFileHandler
class. The specifiedfile is opened and used as the stream for logging. Ifmode is not specified,'a'
is used. Ifencoding is notNone
, it is used to open the filewith that encoding. Ifdelay is true, then file opening is deferred until thefirst call toemit()
. By default, the file grows indefinitely. Iferrors is provided, it determines how encoding errors are handled.You can use themaxBytes andbackupCount 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 nearlymaxBytes in length; but if either ofmaxBytes orbackupCount is zero, rollover never occurs, so you generally wantto setbackupCount to at least 1, and have a non-zeromaxBytes.WhenbackupCount is non-zero, the system will save old log files by appendingthe extensions '.1', '.2' etc., to the filename. For example, with abackupCountof 5 and a base file name of
app.log
, you would getapp.log
,app.log.1
,app.log.2
, up toapp.log.5
. The file beingwritten to is alwaysapp.log
. When this file is filled, it is closedand renamed toapp.log.1
, and if filesapp.log.1
,app.log.2
, etc. exist, then they are renamed toapp.log.2
,app.log.3
etc. respectively.在 3.6 版的變更:As well as string values,
Path
objects are also acceptedfor thefilename argument.在 3.9 版的變更:新增errors 參數。
- doRollover()¶
Does a rollover, as described above.
- emit(record)¶
Outputs the record to the file, catering for rollover as describedpreviously.
TimedRotatingFileHandler¶
TheTimedRotatingFileHandler
class, located in thelogging.handlers
module, supports rotation of disk log files at certaintimed intervals.
- classlogging.handlers.TimedRotatingFileHandler(filename,when='h',interval=1,backupCount=0,encoding=None,delay=False,utc=False,atTime=None,errors=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 ofwhen andinterval.You can use thewhen to specify the type ofinterval. The list of possiblevalues is below. Note that they are not case sensitive.
Value
Type of interval
If/howatTime is used
'S'
Seconds
Ignored
'M'
Minutes
Ignored
'H'
Hours
Ignored
'D'
Days
Ignored
'W0'-'W6'
Weekday (0=Monday)
Used to compute initialrollover time
'midnight'
Roll over at midnight, ifatTime not specified,else at timeatTime
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 theutc argument is true, times in UTC will be used; otherwiselocal time is used.
IfbackupCount is nonzero, at mostbackupCount 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.
Ifdelay is true, then file opening is deferred until the first call to
emit()
.IfatTime is not
None
, it must be adatetime.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, theatTime value is effectively used to compute theinitialrollover, and subsequent rollovers would be calculated via the normalinterval calculation.Iferrors is specified, it's used to determine how encoding errors arehandled.
備註
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 參數。
在 3.6 版的變更:As well as string values,
Path
objects are also acceptedfor thefilename argument.在 3.9 版的變更:新增errors 參數。
- doRollover()¶
Does a rollover, as described above.
- emit(record)¶
Outputs the record to the file, catering for rollover as described above.
- getFilesToDelete()¶
Returns a list of filenames which should be deleted as part of rollover. Theseare the absolute paths of the oldest backup log files written by the handler.
SocketHandler¶
TheSocketHandler
class, located in thelogging.handlers
module,sends logging output to a network socket. The base class uses a TCP socket.
- classlogging.handlers.SocketHandler(host,port)¶
Returns a new instance of the
SocketHandler
class intended tocommunicate with a remote machine whose address is given byhost andport.在 3.4 版的變更:If
port
is specified asNone
, a Unix domain socket is createdusing the value inhost
- otherwise, a TCP socket is created.- close()¶
Closes the socket.
- 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. If the connection was previously lost, re-establishes theconnection. To unpickle the record at the receiving end into a
LogRecord
, use themakeLogRecord()
function.
- handleError()¶
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.
- makeSocket()¶
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
).
- makePickle(record)¶
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))returndatalen+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-stringpacket 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 upafter 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¶
TheDatagramHandler
class, located in thelogging.handlers
module, inherits fromSocketHandler
to support sending logging messagesover UDP sockets.
- classlogging.handlers.DatagramHandler(host,port)¶
Returns a new instance of the
DatagramHandler
class intended tocommunicate with a remote machine whose address is given byhost andport.備註
As UDP is not a streaming protocol, there is no persistent connectionbetween an instance of this handler andhost. For this reason, when using anetwork socket, a DNS lookup might have to be made each time an event islogged, which can introduce some latency into the system. If this affects you,you can do a lookup yourself and initialize this handler using the looked-up IPaddress rather than the hostname.
在 3.4 版的變更:If
port
is specified asNone
, a Unix domain socket is createdusing the value inhost
- 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.
- makeSocket()¶
The factory method of
SocketHandler
is here overridden to createa UDP socket (socket.SOCK_DGRAM
).
- send(s)¶
Send a pickled byte-string to a socket. The format of the sent byte-stringis as described in the documentation for
SocketHandler.makePickle()
.
SysLogHandler¶
TheSysLogHandler
class, located in thelogging.handlers
module,supports sending logging messages to a remote or local Unix syslog.
- classlogging.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 byaddress inthe form of a(host,port)
tuple. Ifaddress 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. Iffacility is not specified,LOG_USER
is used. The type of socket opened depends on thesocktype 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.備註
On macOS 12.x (Monterey), Apple has changed the behaviour of theirsyslog daemon - it no longer listens on a domain socket. Therefore, you cannotexpect
SysLogHandler
to work on this system.Seegh-91070 for more information.
在 3.2 版的變更:新增socktype。
- close()¶
Closes the socket to the remote host.
- createSocket()¶
Tries to create a socket and, if it's not a datagram socket, connect itto the other end. This method is called during handler initialization,but it's not regarded as an error if the other end isn't listening atthis point - the method will be called again when emitting an event, ifthere is no socket at that point.
在 3.11 版被加入.
- emit(record)¶
The record is formatted, and then sent to the syslog server. If exceptioninformation is present, it isnot 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,
append_nul
. This defaults toTrue
(preserving the existingbehaviour) but can be set toFalse
on aSysLogHandler
instancein order for that instance tonot 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 onaSysLogHandler
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 inSysLogHandler
andmirror the values defined in thesys/syslog.h
header file.Priorities
Name (string)
Symbolic value
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
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
- 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¶
TheNTEventLogHandler
class, located in thelogging.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.
- classlogging.handlers.NTEventLogHandler(appname,dllname=None,logtype='Application')¶
Returns a new instance of the
NTEventLogHandler
class. Theappname isused to define the application name as it appears in the event log. Anappropriate registry entry is created using this name. Thedllname 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.
- emit(record)¶
Determines the message ID, event category and event type, and then logsthe message in the NT event log.
- getEventCategory(record)¶
Returns the event category for the record. Override this if you want tospecify your own categories. This version returns 0.
- getEventType(record)¶
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'stypemap attribute.
- getMessageID(record)¶
Returns the message ID for the record. If you are using your own messages,you could do this by having themsg 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¶
TheSMTPHandler
class, located in thelogging.handlers
module,supports sending logging messages to an email address via SMTP.
- classlogging.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 themailhost 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 thecredentials 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 the
smtplib.SMTP.starttls()
method.)A timeout can be specified for communication with the SMTP server using thetimeout argument.
在 3.3 版的變更:新增timeout 參數。
- emit(record)¶
Formats the record and sends it to the specified addressees.
- getSubject(record)¶
If you want to specify a subject line which is record-dependent, overridethis method.
MemoryHandler¶
TheMemoryHandler
class, located in thelogging.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 callingshouldFlush()
to see if the buffer should be flushed. If itshould, thenflush()
is expected to do the flushing.
- classlogging.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.
- flush()¶
For a
BufferingHandler
instance, flushing means that it sets thebuffer to an empty list. This method can be overwritten to implement more usefulflushing behavior.
- shouldFlush(record)¶
Return
True
if the buffer is up to capacity. This method can beoverridden to implement custom flushing strategies.
- classlogging.handlers.MemoryHandler(capacity,flushLevel=ERROR,target=None,flushOnClose=True)¶
Returns a new instance of the
MemoryHandler
class. The instance isinitialized with a buffer size ofcapacity (number of records buffered).IfflushLevel is not specified,ERROR
is used. If notarget isspecified, the target will need to be set usingsetTarget()
before thishandler does anything useful. IfflushOnClose is specified asFalse
,then the buffer isnot 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 版的變更:新增flushOnClose 參數。
- flush()¶
For a
MemoryHandler
instance, flushing means just sending the bufferedrecords to the target, if there is one. The buffer is also cleared whenbuffered records are sent to the target. Override if you want different behavior.
- setTarget(target)¶
Sets the target handler for this handler.
- shouldFlush(record)¶
Checks for buffer full or a record at theflushLevel or higher.
HTTPHandler¶
TheHTTPHandler
class, located in thelogging.handlers
module,supports sending logging messages to a web server, using eitherGET
orPOST
semantics.
- classlogging.handlers.HTTPHandler(host,url,method='GET',secure=False,credentials=None,context=None)¶
Returns a new instance of the
HTTPHandler
class. Thehost can beof the formhost:port
, should you need to use a specific port number. Ifnomethod is specified,GET
is used. Ifsecure is true, a HTTPSconnection will be used. Thecontext parameter may be set to assl.SSLContext
instance to configure the SSL settings used for theHTTPS connection. Ifcredentials 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 版的變更:新增context 參數。
- 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.
- emit(record)¶
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, using
setFormatter()
to specify aFormatter
for aHTTPHandler
has no effect.Instead of callingformat()
, this handler callsmapLogRecord()
and thenurllib.parse.urlencode()
to encode thedictionary in a form suitable for sending to a web server.
QueueHandler¶
在 3.2 版被加入.
TheQueueHandler
class, located in thelogging.handlers
module,supports sending logging messages to a queue, such as those implemented in thequeue
ormultiprocessing
modules.
Along with theQueueListener
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.
- classlogging.handlers.QueueHandler(queue)¶
Returns a new instance of the
QueueHandler
class. The instance isinitialized with the queue to send messages to. Thequeue 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 notrequired tohave the task tracking API, which means that you can useSimpleQueue
instances forqueue.備註
If you are using
multiprocessing
, you should avoid usingSimpleQueue
and instead usemultiprocessing.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
).
- prepare(record)¶
Prepares a record for queuing. The object returned by thismethod is enqueued.
The base implementation formats the record to merge the message,arguments, exception and stack information, if present. It also removesunpickleable items from the record in-place. Specifically, it overwritesthe record's
msg
andmessage
attributes with the mergedmessage (obtained by calling the handler'sformat()
method), andsets theargs
,exc_info
andexc_text
attributestoNone
.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.
備註
The base implementation formats the message with arguments, setsthe
message
andmsg
attributes to the formatted message andsets theargs
andexc_text
attributes toNone
to allowpickling and to prevent further attempts at formatting. This meansthat a handler on theQueueListener
side won't have theinformation to do custom formatting, e.g. of exceptions. You may wishto subclassQueueHandler
and override this method to e.g. avoidsettingexc_text
toNone
. Note that themessage
/msg
/args
changes are related to ensuring the record is pickleable,and you might or might not be able to avoid doing that depending onwhether yourargs
are pickleable. (Note that you may have toconsider not only your own code but also code in any libraries thatyou use.)
- 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.
- listener¶
When created via configuration using
dictConfig()
, thisattribute will contain aQueueListener
instance for use with thishandler. Otherwise, it will beNone
.在 3.12 版被加入.
QueueListener¶
在 3.2 版被加入.
TheQueueListener
class, located in thelogging.handlers
module, supports receiving logging messages from a queue, such as thoseimplemented in thequeue
ormultiprocessing
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 withQueueHandler
.
Along with theQueueHandler
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.
- classlogging.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 notrequired to have thetask tracking API (though it's used if available), which means that you canuseSimpleQueue
instances forqueue.備註
If you are using
multiprocessing
, you should avoid usingSimpleQueue
and instead usemultiprocessing.Queue
.If
respect_handler_level
isTrue
, 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 版的變更:新增
respect_handler_level
引數。- dequeue(block)¶
Dequeues a record and return it, optionally blocking.
The base implementation uses
get()
. You may want to override thismethod if you want to use timeouts or work with custom queueimplementations.
- prepare(record)¶
Prepare a record for handling.
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.
- handle(record)¶
Handle a record.
This just loops through the handlers offering them the recordto handle. The actual object passed to the handlers is that whichis returned from
prepare()
.
- start()¶
Starts the listener.
This starts up a background thread to monitor the queue forLogRecords to process.
在 3.13.3 (unreleased) 版的變更:Raises
RuntimeError
if called and the listener is alreadyrunning.
- stop()¶
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, 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 reference for the logging module.
logging.config
模組Configuration API for the logging module.