o ?Og@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl Z ddlZddlZdZdZdZdZdZdZd ZGd d d ejZGd d d eZGdddeZGdddejZGdddejZGdddeZGdddejZGdddejZ GdddejZ!GdddejZ"GdddejZ#Gd d!d!e#Z$Gd"d#d#ejZ%Gd$d%d%e&Z'dS)&z Additional handlers for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved. To use, simply 'import logging.handlers' and log away! N)ST_DEVST_INOST_MTIMEi<#i=#i>#i?#iQc@s:eZdZdZdZdZd ddZddZdd Zd d Z dS) BaseRotatingHandlerz Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. NFcCs.tjj||||||d||_||_||_dS)zA Use the specified filename for streamed logging modeencodingdelayerrorsN)logging FileHandler__init__rr r selffilenamerr r r r7/opt/alt/python310/lib64/python3.10/logging/handlers.pyr6s  zBaseRotatingHandler.__init__cCsFz||r |tj||WdSty"||YdSw)z Emit a record. Output the record to the file, catering for rollover as described in doRollover(). N)shouldRollover doRolloverr r emit Exception handleErrorrrecordrrrrAs  zBaseRotatingHandler.emitcCs t|js |}|S||}|S)a 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. :param default_name: The default name for the log file. )callablenamer)rZ default_nameresultrrrrotation_filenameOs  z%BaseRotatingHandler.rotation_filenamecCs:t|jstj|rt||dSdS|||dS)aL 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. :param source: The source filename. This is normally the base filename, e.g. 'test.log' :param dest: The destination filename. This is normally what the source is rotated to, e.g. 'test.log.1'. N)rrotatorospathexistsrename)rsourcedestrrrrotatebs  zBaseRotatingHandler.rotate)NFN) __name__ __module__ __qualname____doc__rrrrrr&rrrrr-s   rc@s.eZdZdZ  d ddZdd Zd d ZdS) RotatingFileHandlerz Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. arNFcCsD|dkrd}d|vrt|}tj||||||d||_||_dS)a Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. 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", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, 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. If maxBytes is zero, rollover never occurs. rr,br r r N)io text_encodingrrmaxBytes backupCount)rrrr1r2r r r rrrr|s   zRotatingFileHandler.__init__cCs|jr |jd|_|jdkrct|jdddD]/}|d|j|f}|d|j|df}tj|rHtj|rBt |t ||q||jd}tj|r\t || |j||j sm| |_dSdS)z< Do a rollover, as described in __init__(). Nrz%s.%dz.1)streamcloser2ranger baseFilenamer r!r"remover#r&r _open)riZsfndfnrrrrs*         zRotatingFileHandler.doRollovercCsztj|jrtj|jsdS|jdur||_|jdkr;d||}|j dd|j t ||jkr;dSdS)z Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. FNrz%s T) r r!r"r8isfiler5r:r1formatseektelllenrrmsgrrrrs   z"RotatingFileHandler.shouldRollover)r,rrNFN)r'r(r)r*rrrrrrrr+ws $ r+c@s@eZdZdZ   dddZd d Zd d Zd dZddZdS)TimedRotatingFileHandlerz Handler for logging to a file, rotating the log file at certain timed intervals. If backupCount is > 0, when rollover is done, no more than backupCount files are kept - the oldest ones are deleted. hr3rNFc Cst|}tj||d||| d||_||_||_||_|jdkr-d|_ d|_ d|_ nt|jdkrra)rrrcrrrrXs   z'TimedRotatingFileHandler.shouldRolloverc Cs$tj|j\}}t|}g}tj|\}}|d}t|}|D]S} |jdur0| |s/q"n| |sK| |rKt| |dkrK| |d sKq"| d||kru| |d} | d} | D]} |j | rt| tj|| nq`q"t||jkrg}|S||dt||j}|S)z Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). .Nr3)r r!splitr8listdirsplitextrBrrXendswithisdigitrWmatchappendjoinr2sort) rZdirNameZbaseNameZ fileNamesrneprefixZplenZfileNamerVpartspartrrrgetFilesToDeleteks:       z)TimedRotatingFileHandler.getFilesToDeletec Csn|jr |jd|_tt}t|d}|j|j}|jr't|}nt|}|d}||krB|r9d}nd}t||}| |j dt |j |}t j|r\t |||j ||jdkrt|D]}t |ql|js|||_||} | |kr| |j} | |ks|jdks|jdr|jst| d} || kr|sd}nd}| |7} | |_dS) ax do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. Nr4rKrirtrrMrN)r5r6rZr`rkrbrUrSrjrr8strftimerVr r!r"r9r&r2rr r:rarRrX) rrnrqrcZ timeTupleZdstThenrsr<srprrrrrrsL                z#TimedRotatingFileHandler.doRollover)rFr3rNFFNN) r'r(r)r*rrarrrrrrrrEs =I *rEc@s6eZdZdZ  d ddZddZd d Zd d ZdS)WatchedFileHandlera A handler for logging to a file, which watches the file to see if it has changed while in use. This can happen because of usage of programs such as newsyslog and logrotate which perform log file rotation. This handler, intended for use under Unix, watches the file to see if it has changed since the last emit. (A file has changed if its device or inode have changed.) If it 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 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. This handler is based on a suggestion and patch by Chad J. Schroeder. r,NFcCsBd|vr t|}tjj||||||dd\|_|_|dS)Nr-r)r4r4)r/r0r r rdevino _statstreamrrrrrs    zWatchedFileHandler.__init__cCs4|jrt|j}|t|t|_|_dSdSN)r5r fstatfilenorrrrrZsresrrrrszWatchedFileHandler._statstreamcCszt|j}Wn tyd}Ynw|r$|t|jks$|t|jkrC|jdurA|j |j d|_| |_| dSdSdS)z Reopen log file if needed. Checks if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. N) r r_r8FileNotFoundErrorrrrrr5flushr6r:rrrrrreopenIfNeededs        z!WatchedFileHandler.reopenIfNeededcCs|tj||dS)z Emit a record. If underlying file has changed, reopen the file before emitting the record to it. N)rr r rrrrrrszWatchedFileHandler.emit)r,NFN)r'r(r)r*rrrrrrrrrs   rc@sReZdZdZddZdddZddZd d Zd d Zd dZ ddZ ddZ dS) SocketHandlera A handler class which writes logging records, in pickle format, to a streaming socket. The socket is kept open across logging calls. If the peer resets it, an attempt is made to reconnect on the next call. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. cCsZtj|||_||_|dur||_n||f|_d|_d|_d|_d|_ d|_ d|_ dS)a Initializes the handler with a specific host address and port. When the attribute *closeOnError* is set to True - if a socket error occurs, the socket is silently closed and then reopened on the next logging call. NFg?g>@g@) r Handlerrhostportaddresssock closeOnError retryTime retryStartretryMax retryFactorrrrrrrrs   zSocketHandler.__init__r3cCsd|jdurtj|j|d}|Sttjtj}||z ||jW|Sty1| w)zr A factory method which allows subclasses to define the precise type of socket they want. Ntimeout) rsocketZcreate_connectionrAF_UNIX SOCK_STREAMZ settimeoutconnectOSErrorr6)rrrrrr makeSocket7s    zSocketHandler.makeSocketcCst}|jdur d}n||jk}|rJz ||_d|_WdStyI|jdur/|j|_n|j|j|_|j|jkr@|j|_||j|_YdSwdS)z Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored. NT) r`rrrrrZ retryPeriodrr)rZnowZattemptrrr createSocketHs"        zSocketHandler.createSocketcCsT|jdur ||jr(z |j|WdSty'|jd|_YdSwdS)z Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. N)rrsendallrr6rrrrrsendds    zSocketHandler.sendcCsj|j}|r ||}t|j}||d<d|d<d|d<|ddt|d}t dt |}||S)z Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. rDNargsexc_infomessager3z>L) rr?dict__dict__Z getMessagepoppickledumpsstructZpackrB)rrZeiZdummydrZslenrrr makePicklews     zSocketHandler.makePicklecCs2|jr|jr|jd|_dStj||dS)z Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event. N)rrr6r rrrrrrrs   zSocketHandler.handleErrorcCs:z ||}||WdSty||YdSw)a Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. N)rrrr)rrrrrrrs   zSocketHandler.emitcCsF|z|j}|rd|_|tj|W|dS|wz$ Closes the socket. N)acquirerr6r rrelease)rrrrrr6szSocketHandler.closeN)r3) r'r(r)r*rrrrrrrr6rrrrrs  rc@s(eZdZdZddZddZddZdS) DatagramHandlera A handler class which writes logging records, in pickle format, to a datagram socket. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. cCst|||d|_dS)zP Initializes the handler with a specific host address and port. FN)rrrrrrrrs zDatagramHandler.__init__cCs*|jdur tj}ntj}t|tj}|S)zu The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). N)rrrZAF_INET SOCK_DGRAM)rZfamilyrrrrrs zDatagramHandler.makeSocketcCs&|jdur ||j||jdS)z Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence. N)rrsendtorrrrrrs zDatagramHandler.sendN)r'r(r)r*rrrrrrrrs   rc @seZdZdZdZdZdZdZdZdZ dZ d Z dZ dZ dZdZdZdZdZd Zd Zd Zd Zd ZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#eeee eeee e eeed Z$idededededed ed!e d"ed#ed$ed%ed&ed'ed(ed)e d*ed+eeeee e!e"e#d,Z%d-d.d/d0d1d2Z&d3e'fe d4fd5d6Z(d7d8Z)d9d:Z*d;d<Z+d=d>Z,d?Z-d@Z.dAdBZ/d4S)C SysLogHandlera A handler class which sends formatted logging records to a syslog server. Based on Sam Rushing's syslog module: http://www.nightmare.com/squirl/python-ext/misc/syslog.py Contributed by Nicolas Untz (after which minor refactoring changes have been made). rr3r=rdrerfrgrh ) ZalertZcritcriticaldebugZemergerrerrorinfoZnoticeZpanicwarnwarningZauthZauthprivZconsoleZcrondaemonZftpZkernZlprZmailZnewsZntpZsecurityz solaris-cronZsysloguserZuucpZlocal0)Zlocal1Zlocal2Zlocal3Zlocal4Zlocal5Zlocal6Zlocal7rrrrr)DEBUGINFOWARNINGERRORCRITICALZ localhostNc Cs(tj|||_||_||_t|tr*d|_z| |WdSt y)YdSwd|_|dur4t j }|\}}t ||d|}|sFt d|D]=}|\}}} } } d} } zt ||| } |t jkrg| | Wnt y}z|} | dur{| WYd}~qHd}~ww| dur| | |_ ||_dS)a Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For Unix sockets, you can also specify a socktype of None, in which case socket.SOCK_DGRAM will be used, falling back to socket.SOCK_STREAM. TFNrz!getaddrinfo returns an empty list)r rrrfacilitysocktype isinstancestr unixsocket_connect_unixsocketrrrZ getaddrinforrr6)rrrrrrZressresZafproto_ZsarrexcrrrrPsH      zSysLogHandler.__init__c Cs|j}|dur tj}ttj||_z |j|||_WdStyV|j|jdur0tj}ttj||_z |j|||_WYdStyU|jwwr)rrrrrrr6r)rrZ use_socktyperrrrs*        z!SysLogHandler._connect_unixsocketcCs4t|tr |j|}t|tr|j|}|d>|BS)z Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers. rd)rrfacility_namespriority_names)rrZpriorityrrrencodePrioritys     zSysLogHandler.encodePrioritycCs8|z|jtj|W|dS|wr)rrr6r rrrrrrr6s  zSysLogHandler.closecCs|j|dS)aK Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081). r) priority_mapget)rZ levelNamerrr mapPriorityszSysLogHandler.mapPriorityTcCszs||}|jr|j|}|jr|d7}d||j||j}|d}|d}||}|jrZz |j |WWdSt yY|j | |j|j |YWdSw|jt jkrk|j ||jWdS|j |WdSty||YdSw)z Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. z<%d>utf-8N)r?ident append_nulrrrZ levelnameencoderrrrr6rrrrrrrr)rrrDZpriorrrrs4           zSysLogHandler.emit)0r'r(r)r*Z LOG_EMERGZ LOG_ALERTZLOG_CRITZLOG_ERRZ LOG_WARNINGZ LOG_NOTICEZLOG_INFOZ LOG_DEBUGZLOG_KERNZLOG_USERZLOG_MAILZ LOG_DAEMONZLOG_AUTHZ LOG_SYSLOGZLOG_LPRZLOG_NEWSZLOG_UUCPZLOG_CRONZ LOG_AUTHPRIVZLOG_FTPZLOG_NTPZ LOG_SECURITYZ LOG_CONSOLEZ LOG_SOLCRONZ LOG_LOCAL0Z LOG_LOCAL1Z LOG_LOCAL2Z LOG_LOCAL3Z LOG_LOCAL4Z LOG_LOCAL5Z LOG_LOCAL6Z LOG_LOCAL7rrrSYSLOG_UDP_PORTrrrr6rrrrrrrrrs       6    rc@s,eZdZdZ d ddZddZdd ZdS) SMTPHandlerzK A handler class which sends an SMTP email for each logging event. N@cCstj|t|ttfr|\|_|_n|d|_|_t|ttfr)|\|_|_ nd|_||_ t|t r7|g}||_ ||_ ||_||_dS)ax Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To specify the use of a secure protocol (TLS), pass in a tuple for the secure argument. This will only be used when authentication credentials are supplied. The tuple will 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 `starttls` method). A timeout in seconds can be specified for the SMTP connection (the default is one second). N)r rrrlisttuplemailhostmailportusernamepasswordfromaddrrtoaddrssubjectsecurer)rrrrr credentialsrrrrrrs   zSMTPHandler.__init__cCs|jS)z Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. )rrrrr getSubjectszSMTPHandler.getSubjectcCszpddl}ddlm}ddl}|j}|s|j}|j|j||jd}|}|j |d<d |j |d<| ||d<|j |d <||||jre|jdur]||j|j|||j|j|||WdSty||YdSw) zd Emit a record. Format the record and send it to the specified addressees. rN) EmailMessagerZFrom,ZToZSubjectZDate)smtplibZ email.messagerZ email.utilsrZ SMTP_PORTZSMTPrrrr|rrZutilsrkZ set_contentr?rrZehloZstarttlsZloginrZ send_messagequitrr)rrrrZemailrZsmtprDrrrrs2      zSMTPHandler.emit)NNr)r'r(r)r*rrrrrrrrs  # rc@sBeZdZdZdddZddZdd Zd d Zd d ZddZ dS)NTEventLogHandlera A handler class which sends events to the NT Event Log. Adds a registry entry for the specified application name. If no dllname is provided, win32service.pyd (which contains some basic message placeholders) is used. 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 which contains the message definitions you want to use in the event log. N Applicationc Cstj|zsddl}ddl}||_||_|s0tj |jj }tj |d}tj |dd}||_ ||_ z |j|||Wnty[}zt|dddkrQWYd}~nd}~ww|j|_tj|jtj|jtj|jtj|jtj|ji|_WdStytdd|_YdSw)Nrzwin32service.pydZwinerrorrfzWThe Python Win32 extensions for NT (service, event logging) appear not to be available.)r rrwin32evtlogutil win32evtlogappname_welur r!ru__file__r|dllnamelogtypeZAddSourceToRegistryrgetattrZEVENTLOG_ERROR_TYPEdeftyperZEVENTLOG_INFORMATION_TYPErrZEVENTLOG_WARNING_TYPErrtypemap ImportErrorprint)rrr r rrrrrrrAs<    zNTEventLogHandler.__init__cCdS)ay Return the message ID for the event 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 formatting 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. r3rrrrr getMessageIDdzNTEventLogHandler.getMessageIDcCr)z Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. rrrrrrgetEventCategorynsz"NTEventLogHandler.getEventCategorycCs|j|j|jS)a Return 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. )rrlevelnor rrrr getEventTypews zNTEventLogHandler.getEventTypecCsp|jr6z#||}||}||}||}|j|j||||gWdSty5||YdSwdS)z Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. N) rrrrr?Z ReportEventrrr)rridcattyperDrrrrs     zNTEventLogHandler.emitcCstj|dS)aS Clean up this handler. 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. N)r rr6rrrrr6s zNTEventLogHandler.close)Nr) r'r(r)r*rrrrrr6rrrrr7s #   rc@s6eZdZdZ  d ddZddZd d Zd d ZdS) HTTPHandlerz^ A class which sends records to a web server, using either GET or POST semantics. GETFNcCs`tj||}|dvrtd|s|durtd||_||_||_||_||_ ||_ dS)zr Initialize the instance with the host, the request URL, and the method ("GET" or "POST") )rPOSTzmethod must be GET or POSTNz3context parameter only makes sense with secure=True) r rrrQrYrurlmethodrrcontext)rrrrrrrrrrrs   zHTTPHandler.__init__cCs|jS)z Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. )rrrrr mapLogRecordszHTTPHandler.mapLogRecordcCs2ddl}|r|jj||jd}|S|j|}|S)z get a HTTP[S]Connection. Override when a custom connection is required, for example if there is a proxy. rN)r)Z http.clientZclientZHTTPSConnectionrZHTTPConnection)rrrZhttpZ connectionrrr getConnections  zHTTPHandler.getConnectionc CsNzddl}|j}|||j}|j}|j||}|jdkr4| ddkr*d}nd}|d||f}| |j|| d}|dkrJ|d|}|jdkr_| d d | d t t ||jrddl} d |jd } d| | d} | d| ||jdkr||d |WdSty||YdSw)zk Emit a record. Send the record to the web server as a percent-encoded dictionary rNr?&z%c%s:rz Content-typez!application/x-www-form-urlencodedzContent-lengthz%s:%srzBasic asciiZ Authorization)Z urllib.parserr!rrparseZ urlencoder rfindZ putrequestZ putheaderrrBrbase64rZ b64encodestripdecodeZ endheadersrZ getresponserr) rrZurllibrrFrdatasepr;r(rrrrrs@       zHTTPHandler.emit)rFNN)r'r(r)r*rr r!rrrrrrs  rc@s8eZdZdZddZddZddZdd Zd d Zd S) BufferingHandlerz A handler class which buffers logging records in memory. Whenever each record is added to the buffer, a check is made to see if the buffer should be flushed. If it should, then flush() is expected to do what's needed. cCstj|||_g|_dS)z> Initialize the handler with the buffer size. N)r rrcapacitybuffer)rr.rrrrs  zBufferingHandler.__init__cCst|j|jkS)z Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. )rBr/r.rrrr shouldFlush szBufferingHandler.shouldFlushcCs&|j|||r|dSdS)z Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. N)r/r{r0rrrrrrs   zBufferingHandler.emitcCs,|z |jW|dS|w)zw Override to implement custom flushing behaviour. This version just zaps the buffer to empty. N)rr/clearrrrrrrs zBufferingHandler.flushc Cs*z |Wtj|dStj|w)zp Close the handler. This version just flushes and chains to the parent class' close(). N)rr rr6rrrrr6*s zBufferingHandler.closeN) r'r(r)r*rr0rrr6rrrrr-s  r-c@sBeZdZdZejddfddZddZdd Zd d Z d d Z dS) MemoryHandlerz A handler class which buffers 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. NTcCs"t||||_||_||_dS)a; Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone! The ``flushOnClose`` argument is ``True`` for backward compatibility reasons - the old behaviour is that when the handler is closed, the buffer is flushed, even if the flush level hasn't been exceeded nor the capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. N)r-r flushLeveltarget flushOnClose)rr.r3r4r5rrrr;s  zMemoryHandler.__init__cCst|j|jkp |j|jkS)zP Check for buffer full or a record at the flushLevel or higher. )rBr/r.rr3rrrrr0Os zMemoryHandler.shouldFlushcCs(|z ||_W|dS|w)z: Set the target handler for this handler. N)rr4r)rr4rrr setTargetVszMemoryHandler.setTargetcCsX|z"|jr |jD]}|j|q |jW|dSW|dS|w)z For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour. The record buffer is also cleared by this operation. N)rr4r/handler1rrrrrr`s   zMemoryHandler.flushcCstz!|jr|W|zd|_t|W|dS|w|zd|_t|W|w|w)zi Flush, if appropriately configured, set the target to None and lose the buffer. N)r5rrr4r-r6rrrrrr6qs  zMemoryHandler.close) r'r(r)r*r rrr0r6rr6rrrrr25s  r2c@s0eZdZdZddZddZddZdd Zd S) QueueHandlera This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. This code is new in Python 3.2, but this class can be copy pasted into user code for use with earlier Python versions. cCstj|||_dS)zA Initialise an instance, using the passed queue. N)r rrqueue)rr9rrrrs  zQueueHandler.__init__cCs|j|dS)z Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue implementations. N)r9 put_nowaitrrrrenqueueszQueueHandler.enqueuecCs<||}t|}||_||_d|_d|_d|_d|_|S)a Prepares a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and arguments, and 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. N)r?copyrrDrrZexc_textZ stack_inforCrrrprepares  zQueueHandler.preparecCs6z |||WdSty||YdSw)zm Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. N)r;r=rrrrrrrs  zQueueHandler.emitN)r'r(r)r*rr;r=rrrrrr8s   r8c@sZeZdZdZdZddddZddZd d Zd d Zd dZ ddZ ddZ ddZ dS) QueueListenerz This class implements an internal threaded listener which watches for LogRecords being added to a queue, removes them and passes them to a list of handlers for processing. NF)respect_handler_levelcGs||_||_d|_||_dS)zW Initialise an instance with the specified queue and handlers. N)r9handlers_threadr?)rr9r?r@rrrrs zQueueListener.__init__cCs |j|S)z Dequeue 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. )r9r)rblockrrrdequeues zQueueListener.dequeuecCs&tj|jd|_}d|_|dS)z Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. )r4TN) threadingZThread_monitorrArstart)rrcrrrrFs zQueueListener.startcCs|S)a Prepare a record for handling. This method 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. rrrrrr=rzQueueListener.preparecCs@||}|jD]}|jsd}n|j|jk}|r||qdS)z| Handle a record. This just loops through the handlers offering them the record to handle. TN)r=r@r?rlevelr7)rrZhandlerZprocessrrrr7s    zQueueListener.handlecCsl|j}t|d} z |d}||jur|r|WdS|||r(|Wn tjy4YdSwq )z Monitor the queue for records, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. task_doneTN)r9hasattrrC _sentinelrHr7ZEmpty)rqZ has_task_donerrrrrEs"    zQueueListener._monitorcCs|j|jdS)z This is used to enqueue the sentinel record. The base implementation uses put_nowait. You may want to override this method if you want to use timeouts or work with custom queue implementations. N)r9r:rJrrrrenqueue_sentinelszQueueListener.enqueue_sentinelcCs||jd|_dS)a  Stop 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. N)rLrAr|rrrrstop)s  zQueueListener.stop) r'r(r)r*rJrrCrFr=r7rErLrMrrrrr>s     r>)(r*r/r rr rrr`r\r_rrrr9rDr<ZDEFAULT_TCP_LOGGING_PORTZDEFAULT_UDP_LOGGING_PORTZDEFAULT_HTTP_LOGGING_PORTZDEFAULT_SOAP_LOGGING_PORTrZSYSLOG_TCP_PORTrlr rr+rErrrrrrrrr-r2r8objectr>rrrrs>@ JS~J(*PkZ9MF