a ÕDOgìã@szdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z ddl Z ddl Z ddlZdZdZdZdZdZdZd ZGd d „d ejƒZGd d „d eƒZGdd„deƒZGdd„dejƒZGdd„dejƒZGdd„deƒZGdd„dejƒZGdd„dejƒZGdd„dejƒZ Gdd„dejƒZ!Gdd„dejƒZ"Gd d!„d!e"ƒZ#Gd"d#„d#ejƒZ$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_DEVÚST_INOÚST_MTIMEi<#i=#i>#i?#ié€Qc@s:eZdZdZdZdZd dd„Zdd„Zdd „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 ©ÚmodeÚencodingÚdelayÚerrorsN)ÚloggingÚ FileHandlerÚ__init__rr r ©ÚselfÚfilenamerr r r ©rú5/opt/alt/python39/lib64/python3.9/logging/handlers.pyr6s þzBaseRotatingHandler.__init__cCsFz$| |¡r| ¡tj ||¡Wnty@| |¡Yn0dS)z„ Emit a record. Output the record to the file, catering for rollover as described in doRollover(). N)ÚshouldRolloverÚ doRolloverr r ÚemitÚ ExceptionÚ handleError©rÚrecordrrrrAs   zBaseRotatingHandler.emitcCst|jƒs|}n | |¡}|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. )ÚcallableÚnamer)rZ default_nameÚresultrrrÚrotation_filenameOs  z%BaseRotatingHandler.rotation_filenamecCs4t|jƒs$tj |¡r0t ||¡n | ||¡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)rÚrotatorÚosÚpathÚexistsÚrename)rÚsourceÚdestrrrÚrotatebs  zBaseRotatingHandler.rotate)NFN) Ú__name__Ú __module__Ú __qualname__Ú__doc__rrrrrr&rrrrr-s rc@s*eZdZdZd dd„Zdd „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. ÚarNFcCs2|dkr d}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,©r r r N)rrÚmaxBytesÚ backupCount)rrrr.r/r r r rrrr|s ÿzRotatingFileHandler.__init__cCsÚ|jr|j ¡d|_|jdkrÆt|jdddƒD]^}| d|j|f¡}| d|j|df¡}tj |¡r2tj |¡r„t  |¡t  ||¡q2| |jd¡}tj |¡r¸t  |¡|  |j|¡|j sÖ|  ¡|_dS)z< Do a rollover, as described in __init__(). Nrééÿÿÿÿz%s.%dz.1)ÚstreamÚcloser/ÚrangerÚ baseFilenamer r!r"Úremover#r&r Ú_open)rÚiZsfnÚdfnrrrržs&   ÿ     zRotatingFileHandler.doRollovercCsztj |j¡r tj |j¡s dS|jdur4| ¡|_|jdkrvd| |¡}|j  dd¡|j  ¡t |ƒ|jkrvdSdS)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"r5Úisfiler2r7r.ÚformatÚseekÚtellÚlen©rrÚmsgrrrrµs   z"RotatingFileHandler.shouldRollover)r,rrNFN)r'r(r)r*rrrrrrrr+ws ÿ "r+c@s:eZdZdZddd„Zd d „Zd d „Zd d„Zdd„ZdS)Ú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. Úhr0rNFc Csœtj||d||| d| ¡|_||_||_||_|jdkrPd|_d|_d|_ nî|jdkrnd|_d |_d |_ nÐ|jd krŒd |_d |_d|_ n²|jdks |jdkr´d|_d|_d|_ nŠ|j  d¡r0d|_t |jƒdkrät d|jƒ‚|jddks|jddkrt d|jƒ‚t |jdƒ|_d|_d|_ nt d|jƒ‚t |j tj¡|_ |j||_|j}tj |¡r€t |¡t} n t t ¡ƒ} | | ¡|_dS)Nr,r-ÚSr0z%Y-%m-%d_%H-%M-%Sz-^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$ÚMé<z%Y-%m-%d_%H-%Mz'^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$ÚHéz %Y-%m-%d_%Hz!^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$ÚDÚMIDNIGHTrz%Y-%m-%dz^\d{4}-\d{2}-\d{2}(\.\w+)?$ÚWi€: r:zHYou must specify a day for weekly rollover from 0 to 6 (0 is Monday): %sÚ0Ú6z-Invalid day specified for weekly rollover: %sz'Invalid rollover interval specified: %s)rrÚupperÚwhenr/ÚutcÚatTimeÚintervalÚsuffixÚextMatchÚ startswithr?Ú ValueErrorÚintÚ dayOfWeekÚreÚcompileÚASCIIr5r r!r"ÚstatrÚtimeÚcomputeRolloverÚ rolloverAt) rrrOrRr/r r rPrQr ÚtrrrrÐsP ÿ       z!TimedRotatingFileHandler.__init__cCsd||j}|jdks"|j d¡r`|jr4t |¡}n t |¡}|d}|d}|d}|d}|jdurnt}n |jj d|jj d|jj }||d|d|} | d krÂ| t7} |d d }|| }|j d¡r`|} | |j kr`| |j krþ|j | } nd| |j d } || d } |js\|d } t | ¡d }| |kr\| sPd}nd}| |7} | }|S)zI Work out the rollover time based on the specified time. rJrKééééNrFrr0érr1éðñÿÿrH) rRrOrUrPr]ÚgmtimeÚ localtimerQÚ _MIDNIGHTZhourZminuteÚsecondrX)rÚ currentTimerr`Z currentHourZ currentMinuteZ currentSecondZ currentDayZ rotate_tsÚrZdayZ daysToWaitÚ newRolloverAtÚdstNowÚ dstAtRolloverÚaddendrrrr^ sL    ÿÿ      z(TimedRotatingFileHandler.computeRollovercCs>tj |j¡r tj |j¡s dStt ¡ƒ}||jkr:dSdS)z± Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same FT)r r!r"r5r;rWr]r_)rrr`rrrrUs   z'TimedRotatingFileHandler.shouldRolloverc Cs$tj |j¡\}}t |¡}g}tj |¡\}}|d}t|ƒ}|D]¦} |jdur`|  |¡s–qDn6|  |¡s–|   |¡r–t| ƒ|dkr–| |d  ¡s–qD| d|…|krD| |d…} |  d¡} | D](} |j   | ¡rÀ|  tj || ¡¡qDqÀqDt|ƒ|jkrg}n| ¡|dt|ƒ|j…}|S)z Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). Ú.Nr0)r r!Úsplitr5ÚlistdirÚsplitextr?rrUÚendswithÚisdigitrTÚmatchÚappendÚjoinr/Úsort) rZdirNameZbaseNameZ fileNamesrÚnÚeÚprefixZplenZfileNamerSÚpartsÚpartrrrÚgetFilesToDeleteds8   ÿÿ   z)TimedRotatingFileHandler.getFilesToDeletec Csv|jr|j ¡d|_tt ¡ƒ}t |¡d}|j|j}|jrNt |¡}n6t |¡}|d}||kr„|rrd}nd}t ||¡}|  |j dt  |j |¡¡}t j |¡r¸t  |¡| |j |¡|jdkrè| ¡D]}t  |¡qØ|jsø| ¡|_| |¡} | |kr| |j} q|jdks4|j d¡rl|jslt | ¡d} || krl|s`d}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. Nr1rHrfrqrrJrK)r2r3rWr]rhr_rRrPrgrr5ÚstrftimerSr r!r"r6r&r/r€r r7r^rOrU) rrkrnr`Z timeTupleZdstThenrpr9ÚsrmrorrrrŽsJ       ÿ        " z#TimedRotatingFileHandler.doRollover)rCr0rNFFNN) r'r(r)r*rr^rr€rrrrrrBÈsþ <I*rBc@s2eZdZdZd dd„Zdd„Zd 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,NFcCs0tjj||||||dd\|_|_| ¡dS)Nr)r1r1)r r rÚdevÚinoÚ _statstreamrrrrrÔs  þ zWatchedFileHandler.__init__cCs0|jr,t |j ¡¡}|t|t|_|_dS©N)r2r ÚfstatÚfilenorrr„r…©rZsresrrrr†ÜszWatchedFileHandler._statstreamcCs‚zt |j¡}Wnty&d}Yn0|rH|t|jksH|t|jkr~|jdur~|j  ¡|j  ¡d|_|  ¡|_|  ¡dS)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\r5ÚFileNotFoundErrorrr„rr…r2Úflushr3r7r†rŠrrrÚreopenIfNeededás        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 rrrrrrýszWatchedFileHandler.emit)r,NFN)r'r(r)r*rr†rrrrrrrƒÀsÿ rƒc@sReZdZdZdd„Zddd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z 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 ÚHandlerrÚhostÚportÚaddressÚsockÚ closeOnErrorÚ retryTimeÚ retryStartÚretryMaxÚ retryFactor©rrr‘rrrrs  zSocketHandler.__init__r0cCsh|jdurtj|j|d}nHt tjtj¡}| |¡z| |j¡Wntyb|  ¡‚Yn0|S)zr A factory method which allows subclasses to define the precise type of socket they want. N©Útimeout) r‘ÚsocketZcreate_connectionr’ÚAF_UNIXÚ SOCK_STREAMZ settimeoutÚconnectÚOSErrorr3)rr›rrrrÚ makeSocket.s   zSocketHandler.makeSocketcCs”t ¡}|jdurd}n ||jk}|rz| ¡|_d|_WnTtyŽ|jdur\|j|_n"|j|j|_|j|jkr~|j|_||j|_Yn0dS)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]r•r¡r“r r–Z retryPeriodr˜r—)rZnowZattemptrrrÚ createSocket?s        zSocketHandler.createSocketcCsP|jdur| ¡|jrLz|j |¡Wn"tyJ|j ¡d|_Yn0dS)z™ Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. N)r“r¢Úsendallr r3©rr‚rrrÚsend[s   zSocketHandler.sendcCsj|j}|r| |¡}t|jƒ}| ¡|d<d|d<d|d<| dd¡t |d¡}t  dt |ƒ¡}||S)zŒ Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. rANÚargsÚexc_infoÚmessager0z>L) r§r<ÚdictÚ__dict__Z getMessageÚpopÚpickleÚdumpsÚstructZpackr?)rrZeiZdummyÚdr‚ZslenrrrÚ makePicklens     zSocketHandler.makePicklecCs0|jr|jr|j ¡d|_ntj ||¡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)r”r“r3r rrrrrrr„s  zSocketHandler.handleErrorcCs:z| |¡}| |¡Wnty4| |¡Yn0dS)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)r°r¥rr)rrr‚rrrr’s   zSocketHandler.emitcCsH| ¡z0|j}|r"d|_| ¡tj |¡W| ¡n | ¡0dS©z$ Closes the socket. N)Úacquirer“r3r rÚrelease)rr“rrrr3¡szSocketHandler.closeN)r0) r'r(r)r*rr¡r¢r¥r°rrr3rrrrrŽs  rŽc@s(eZdZdZdd„Zdd„Zdd„ZdS) Ú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)rŽrr”r™rrrrºszDatagramHandler.__init__cCs*|jdurtj}ntj}t |tj¡}|S)zu The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). N)r‘rœrZAF_INETÚ SOCK_DGRAM)rZfamilyr‚rrrr¡Ás  zDatagramHandler.makeSocketcCs&|jdur| ¡|j ||j¡dS)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)r“r¢Úsendtor’r¤rrrr¥Ís zDatagramHandler.sendN)r'r(r)r*rr¡r¥rrrrr´¯s  r´c@s8eZdZdZdZdZdZdZdZdZ dZ d Z dZ dZ dZdZdZdZdZd Zd Zd Zd Zd ZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#eeee eeee e eeedœ Z$eeeeeee eeeeeeee eeeeee e!e"e#dœZ%ddddd d!œZ&d"e'fe d#fd$d%„Z(d&d'„Z)d(d)„Z*d*d+„Z+d,d-„Z,d.Z-d/Z.d0d1„Z/d#S)2Ú 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). rr0r:rarbrcrdreéé é é é é éééééééééé) ZalertZcritÚcriticalÚdebugZemergÚerrÚerrorÚinfoZnoticeZpanicÚwarnÚwarning)ZauthZauthprivZconsoleZcronÚdaemonZftpZkernZlprZmailZnewsZntpZsecurityz solaris-cronZsyslogÚuserZuucpZlocal0Zlocal1Zlocal2Zlocal3Zlocal4Zlocal5Zlocal6Zlocal7rÉrÌrÎrËrÈ)ÚDEBUGÚINFOÚWARNINGÚERRORÚCRITICALZ localhostNc Cs2tj |¡||_||_||_t|tƒrRd|_z|  |¡Wnt yNYn0nÜd|_|durft j }|\}}t   ||d|¡}|sŠt dƒ‚|D]„}|\}}} } } d} } z.t   ||| ¡} |t jkrÌ|  | ¡WqWqŽt y}z |} | durü|  ¡WYd}~qŽd}~00qŽ| 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 rrr’ÚfacilityÚsocktypeÚ isinstanceÚstrÚ unixsocketÚ_connect_unixsocketr rœrµZ getaddrinforžrŸr3)rr’rÖr×rr‘ZressÚresZafÚprotoÚ_ZsarÊr“ÚexcrrrrGsB        zSysLogHandler.__init__c Cs´|j}|durtj}t tj|¡|_z|j |¡||_Wntty®|j ¡|jdur^‚tj}t tj|¡|_z|j |¡||_Wnty¨|j ¡‚Yn0Yn0dSr‡)r×rœrµrrŸr r3rž)rr’Z use_socktyperrrrÛ}s&         z!SysLogHandler._connect_unixsocketcCs4t|tƒr|j|}t|tƒr(|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. ra)rØrÙÚfacility_namesÚpriority_names)rrÖZpriorityrrrÚencodePriority•s     zSysLogHandler.encodePrioritycCs:| ¡z"|j ¡tj |¡W| ¡n | ¡0dSr±)r²rœr3r rr³©rrrrr3¢s  zSysLogHandler.closecCs|j |d¡S)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_mapÚget)rZ levelNamerrrÚ mapPriority­szSysLogHandler.mapPriorityÚTcCsüzÚ| |¡}|jr|j|}|jr*|d7}d| |j| |j¡¡}| d¡}| d¡}||}|jr®z|j   |¡WqØt yª|j   ¡|  |j¡|j   |¡YqØ0n*|jt jkrÌ|j  ||j¡n |j  |¡Wntyö| |¡Yn0dS)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_nulrârÖræZ levelnameÚencoderÚrœr¥r r3rÛr’r×rµr¶r£rr)rrrAZpriorrrrºs0    ÿ       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_LOCAL7ráràräÚSYSLOG_UDP_PORTrrÛrâr3rærêrërrrrrr·Ùs®ôè ûÿ 6   r·c@s*eZdZdZd dd„Zdd„Zdd „ZdS) Ú SMTPHandlerzK A handler class which sends an SMTP email for each logging event. Nç@cCsŠtj |¡t|ttfƒr(|\|_|_n|d|_|_t|ttfƒrR|\|_|_ nd|_||_ t|t ƒrn|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 rrrØÚlistÚtupleÚmailhostÚmailportÚusernameÚpasswordÚfromaddrrÙÚtoaddrsÚsubjectÚsecurer›)rròrör÷røÚ credentialsrùr›rrrrâs  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. )rørrrrÚ getSubjectszSMTPHandler.getSubjectcCszÞddl}ddlm}ddl}|j}|s.|j}|j|j||jd}|ƒ}|j |d<d  |j ¡|d<|  |¡|d<|j  ¡|d <| | |¡¡|jrÊ|jdurº| ¡|j|jŽ| ¡| |j|j¡| |¡| ¡Wntyú| |¡Yn0dS) zd Emit a record. Format the record and send it to the specified addressees. rN)Ú EmailMessageršZFromú,ZToZSubjectZDate)ÚsmtplibZ email.messagerüZ email.utilsróZ SMTP_PORTZSMTPròr›röryr÷rûZutilsrhZ set_contentr<rôrùZehloZstarttlsZloginrõZ send_messageÚquitrr)rrrþrüZemailr‘ZsmtprArrrrs0       zSMTPHandler.emit)NNrï)r'r(r)r*rrûrrrrrrîÞs ÿ # rîc@sBeZdZdZddd„Zdd„Zdd „Zd d „Zd d „Zdd„Z 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 CsÚtj |¡z¨ddl}ddl}||_||_|s`tj  |jj ¡}tj  |d¡}tj  |dd¡}||_ ||_ |j |||¡|j|_tj|jtj|jtj|jtj|jtj|ji|_Wn tyÔtdƒd|_Yn0dS)Nrzwin32service.pydzWThe Python Win32 extensions for NT (service, event logging) appear not to be available.)r rrÚwin32evtlogutilÚ win32evtlogÚappnameÚ_welur r!rrÚ__file__ryÚdllnameÚlogtypeZAddSourceToRegistryZEVENTLOG_ERROR_TYPEÚdeftyperÑZEVENTLOG_INFORMATION_TYPErÒrÓZEVENTLOG_WARNING_TYPErÔrÕÚtypemapÚ ImportErrorÚprint)rrrrrrrrrr8s, û  zNTEventLogHandler.__init__cCsdS)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. r0rrrrrÚ getMessageIDRszNTEventLogHandler.getMessageIDcCsdS)zž Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. rrrrrrÚgetEventCategory\sz"NTEventLogHandler.getEventCategorycCs|j |j|j¡S)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. )r råÚlevelnor rrrrÚ getEventTypees zNTEventLogHandler.getEventTypecCsl|jrhzD| |¡}| |¡}| |¡}| |¡}|j |j||||g¡Wntyf| |¡Yn0dS)z” Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. N) rr rrr<Z ReportEventrrr)rrÚidÚcatÚtyperArrrrrs     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 rr3rãrrrr3ƒs zNTEventLogHandler.close)Nr) r'r(r)r*rr rrrr3rrrrr.s    rc@s2eZdZdZd dd„Zdd„Zd d „Zd d „ZdS)Ú HTTPHandlerz^ A class which sends records to a Web server, using either GET or POST semantics. ÚGETFNcCs`tj |¡| ¡}|dvr$tdƒ‚|s8|dur8tdƒ‚||_||_||_||_||_ ||_ dS)zr Initialize the instance with the host, the request URL, and the method ("GET" or "POST") )rÚPOSTzmethod must be GET or POSTNz3context parameter only makes sense with secure=True) r rrrNrVrÚurlÚmethodrùrúÚcontext)rrrrrùrúrrrrr•s  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. )rªrrrrÚ mapLogRecord©szHTTPHandler.mapLogRecordcCs0ddl}|r |jj||jd}n |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)rrrùZhttpZ connectionrrrÚ getConnection±s  zHTTPHandler.getConnectionc CsVz0ddl}|j}| ||j¡}|j}|j | |¡¡}|jdkrj|  d¡dkrVd}nd}|d||f}|  |j|¡|  d¡}|dkr–|d|…}|jdkrÀ|  d d ¡|  d t t |ƒƒ¡|jrddl} d |j d ¡} d|  | ¡ ¡ d¡} |  d| ¡| ¡|jdkr(| | d ¡¡| ¡WntyP| |¡Yn0dS)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:%srézBasic ÚasciiZ Authorization)Z urllib.parserrrùrÚparseZ urlencoderrÚfindZ putrequestZ putheaderrÙr?rúÚbase64rìZ b64encodeÚstripÚdecodeZ endheadersr¥Z getresponserr) rrZurllibrrCrÚdataÚsepr8r"r‚rrrr¿s>    ÿ   zHTTPHandler.emit)rFNN)r'r(r)r*rrrrrrrrrsÿ rc@s8eZdZdZdd„Zdd„Zdd„Zdd „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 rrÚcapacityÚbuffer)rr(rrrrðs 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. )r?r)r(rrrrÚ shouldFlushøszBufferingHandler.shouldFlushcCs"|j |¡| |¡r| ¡dS)z† Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. N)r)rxr*rŒrrrrrs  zBufferingHandler.emitcCs.| ¡z|j ¡W| ¡n | ¡0dS)zw Override to implement custom flushing behaviour. This version just zaps the buffer to empty. N)r²r)Úclearr³rãrrrrŒ s zBufferingHandler.flushc Cs,z| ¡Wtj |¡ntj |¡0dS)zp Close the handler. This version just flushes and chains to the parent class' close(). N)rŒr rr3rãrrrr3s zBufferingHandler.closeN) r'r(r)r*rr*rrŒr3rrrrr'ês    r'c@sBeZdZdZejddfdd„Zdd„Zdd „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Ú flushLevelÚtargetÚ flushOnClose)rr(r-r.r/rrrr)s zMemoryHandler.__init__cCst|jƒ|jkp|j|jkS)zP Check for buffer full or a record at the flushLevel or higher. )r?r)r(rr-rrrrr*=s ÿzMemoryHandler.shouldFlushcCs*| ¡z||_W| ¡n | ¡0dS)z: Set the target handler for this handler. N)r²r.r³)rr.rrrÚ setTargetDszMemoryHandler.setTargetcCsL| ¡z4|jr2|jD]}|j |¡q|j ¡W| ¡n | ¡0dS)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)r²r.r)Úhandler+r³rrrrrŒNs  zMemoryHandler.flushcCszzB|jr| ¡W| ¡zd|_t |¡W| ¡qv| ¡0n2| ¡zd|_t |¡W| ¡n | ¡00dS)zi Flush, if appropriately configured, set the target to None and lose the buffer. N)r/rŒr²r.r'r3r³rãrrrr3_s  û zMemoryHandler.close) r'r(r)r*r rÔrr*r0rŒr3rrrrr,#sÿ  r,c@s0eZdZdZdd„Zdd„Zdd„Zdd „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 rrÚqueue)rr3rrrr{s 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)r3Ú put_nowaitrrrrÚenqueue‚szQueueHandler.enqueuecCs6| |¡}t |¡}||_||_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<Úcopyr¨rAr¦r§Zexc_textr@rrrÚprepareŒs  zQueueHandler.preparecCs6z| | |¡¡Wnty0| |¡Yn0dS)zm Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. N)r5r7rrrrrrr©s zQueueHandler.emitN)r'r(r)r*rr5r7rrrrrr2ps   r2c@sZeZdZdZdZddœdd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dd„Z dd„Z 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)r3ÚhandlersÚ_threadr9)rr3r9r:rrrr½szQueueListener.__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. )r3rå)rÚblockrrrÚdequeueÇszQueueListener.dequeuecCs&tj|jd|_}d|_| ¡dS)z‰ Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. )r.TN)Ú threadingZThreadÚ_monitorr;rÏÚstart)rr`rrrr@ÐszQueueListener.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. rrrrrr7ÛszQueueListener.preparecCs@| |¡}|jD]*}|js d}n |j|jk}|r| |¡qdS)z| Handle a record. This just loops through the handlers offering them the record to handle. TN)r7r:r9rÚlevelr1)rrZhandlerZprocessrrrr1ås   zQueueListener.handlecCsn|j}t|dƒ}z>| d¡}||jur6|r2| ¡Wqj| |¡|rL| ¡WqtjyfYqjYq0qdS)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)r3Úhasattrr=Ú _sentinelrBr1ZEmpty)rÚqZ has_task_donerrrrr?õs     zQueueListener._monitorcCs|j |j¡dS)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)r3r4rDrãrrrÚenqueue_sentinel szQueueListener.enqueue_sentinelcCs| ¡|j ¡d|_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)rFr;ryrãrrrÚstops zQueueListener.stop) r'r(r)r*rDrr=r@r7r1r?rFrGrrrrr8µs     r8)'r*r rœr r¬r®r]rYr\rrrr3r>r6ZDEFAULT_TCP_LOGGING_PORTZDEFAULT_UDP_LOGGING_PORTZDEFAULT_HTTP_LOGGING_PORTZDEFAULT_SOAP_LOGGING_PORTríZSYSLOG_TCP_PORTrir rr+rBrƒrrŽr´r·rîrrr'r,r2Úobjectr8rrrrÚs< 8JQyH(*PbZ9ME