\d|tdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl Z ddlZddlZdZdZdZdZdZdZd ZGd d ejZGd d eZGddeZGddejZGddejZGddeZGddejZGddejZ GddejZ!GddejZ"GddejZ#Gd d!e#Z$Gd"d#ejZ%Gd$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?#iQc4eZdZdZdZdZddZdZdZdZ 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. NFcztj||||||||_||_||_dS)zA Use the specified filename for streamed logging modeencodingdelayerrorsN)logging FileHandler__init__r r rselffilenamer r r rs !..\python\lib\logging\handlers.pyrzBaseRotatingHandler.__init__6sM $$T8$.6e,2 % 4 4 4    c ||r|tj||dS#t $r||YdSwxYw)z Emit a record. Output the record to the file, catering for rollover as described in doRollover(). N)shouldRollover doRolloverrremit Exception handleErrorrrecords rrzBaseRotatingHandler.emitAs %""6** "!!!   $ $T6 2 2 2 2 2 % % %   V $ $ $ $ $ $ %sA A A0/A0c^t|js|}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. )callablenamer)r default_nameresults rrotation_filenamez%BaseRotatingHandler.rotation_filenameOs3 ## .!FFZZ --F rct|js8tj|rtj||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)r rotatorospathexistsrename)rsourcedests rrotatezBaseRotatingHandler.rotatebsj %% 'w~~f%% ( &$''''' ( ( LL & & & & &r)NFN) __name__ __module__ __qualname____doc__r!r&rrr$r-rrrr-sk EG     % % %&'''''rrc*eZdZdZ d dZdZdZdS) 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. arNFc|dkrd}d|vrtj|}t||||||||_||_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. rr5br r rN)io text_encodingrrmaxBytes backupCount)rrr r;r<r r rs rrzRotatingFileHandler.__init__|sm6 a<<D d??'11H$$T8TH+0 % A A A  &rc|jr |jd|_|jdkr/t|jdz ddD]}|d|j|fz}|d|j|dzfz}t j|rHt j|rt j |t j ||||jdz}t j|rt j || |j||j s| |_dSdS)z< Do a rollover, as described in __init__(). Nrz%s.%dz.1)streamcloser<ranger$ baseFilenamer'r(r)remover*r-r _open)risfndfns rrzRotatingFileHandler.doRolloversq ;  K     DK  a  4+a/B77 ( (,,W8I17M-MNN,,W8I89A8?.?@@7>>#&&(w~~c**' #Ic3'''(():T)ABBCw~~c""  # KK)3 / / /z '**,,DKKK ' 'rctj|jr&tj|jsdS|j||_|jdkrgd||z}|j dd|j t|z|jkrdSdS)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)rCisfiler@rEr;formatseektelllenrrmsgs rrz"RotatingFileHandler.shouldRollovers 7>>$+ , , RW^^DDU5V5V 5 ; **,,DK =1  4;;v...C K  Q " " "{!!CHH, ==tur)r5rrNFN)r.r/r0r1rrrr2rrr4r4ws[DE48"'"'"'"'H'''.rr4c8eZdZdZ d dZdZd Zd Zd 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. hr>rNFc tj|}t||d||| ||_||_||_||_|jdkrd|_ d|_ d|_ n=|jdkrd|_ d |_ d |_ n|jd krd |_ d |_ d|_ n|jdks |jdkrd|_ d|_ d|_ n|j drd|_ t|jdkrtd|jz|jddks|jddkrtd|jzt|jd|_d|_ d|_ ntd|jzt#j|j t"j|_ |j |z|_ |j}t*j|r t+j|t2} n tt5j} || |_dS)Nr5r8Sr>z%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+)?$Hz %Y-%m-%d_%Hz!^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$DMIDNIGHTrz%Y-%m-%dz^\d{4}-\d{2}-\d{2}(\.\w+)?$Wi: rJzHYou must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s06z-Invalid day specified for weekly rollover: %sz'Invalid rollover interval specified: %s)r9r:rrupperwhenr<utcatTimeintervalsuffixextMatch startswithrO ValueErrorint dayOfWeekrecompileASCIIrCr'r(r)statrtimecomputeRollover rolloverAt) rrrardr<r r rbrcrts rrz!TimedRotatingFileHandler.__init__sJ#H--$$T8S8+0 % A A AJJLL &  9  DM-DKLDMM Y#  DM*DKFDMM Y#  #DM'DK@DMM Y#  j!8!8(DM$DK:DMM Y ! !# & & T,DM49~~"" !knrnw!wxxxy|c!!TYq\C%7%7 !PSWS\!\]]] 1..DN$DK:DMMFRSS S 4="(;;  0 $ 7>>( # # !!!(+AADIKK  A..q11rc||jz}|jdks|jdrK|jrt j|}nt j|}|d}|d}|d}|d}|jt}n,|jj dz|jj zdz|jj z}||dz|zdz|zz } | d kr| tz } |d zd z}|| z}|jdrx|} | |j krk| |j kr |j | z } nd| z |j zd z} || d zz} |js4|d } t j| d }| |kr | sd}nd}| |z } | }|S)zI Work out the rollover time based on the specified time. r\r]NrXrr>rr?rZ) rdrargrbrogmtime localtimerc _MIDNIGHThourminutesecondrj)r currentTimer#rr currentHour currentMinute currentSecond currentDay rotate_tsrday daysToWait newRolloverAtdstNow dstAtRolloveraddends rrpz(TimedRotatingFileHandler.computeRolloverst}, 9 " "di&:&:3&?&? "x 0K ,,N;//A$KaDMaDM1J{"% "k.3dk6HH"LK&' kB.>"DA1uuY(1n1  1_F y##C(( + $.((T^++%)^c%9 %&Wt~%=%A $*jL.I$JM84!"2(,}(E(Eb(I !]22#).).)-)V3M*F rc(ttj}||jkrftj|jr@tj|js|||_dSdSdS)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) rirorqr'r(r)rCrKrp)rrrrs rrz'TimedRotatingFileHandler.shouldRolloverXs{      w~~d/00 HY9Z9Z #'"6"6q"9"9u4urctj|j\}}tj|}g}tj|\}}|dz}t |}|D]} |j| |s n^| |sI| |r4t | |dzkr| |dz s| d||krs| |d} | d} | D]Q} |j | r5| tj|| nRt ||jkrg}n3||dt ||jz }|S)z Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). .Nr>)r'r(splitrClistdirsplitextrOr!rgendswithisdigitrfmatchappendjoinr<sort) rdirNamebaseName fileNamesr#neprefixplenfileNamerepartsparts rgetFilesToDeletez)TimedRotatingFileHandler.getFilesToDeleteks GMM$*;<<Jw'' w))1S6{{!  Hz!**844 !++H55(:K:KA:N:NMMTAX..xQ7G7O7O7Q7Q.&((!$%% S))!D}**400 bgll7H&E&EFFF v;;) ) )FF KKMMM;S[[4+;;;>#    IcNNN D%s+++  a  **,,   ! z '**,,DK,,[99 {**)DM9M{** I # #ty';';C'@'@ #$( # N=99"=M&&""FF!F' 'r)rTr>rNFFNN) r.r/r0r1rrprrrr2rrrSrSsDE?C;2;2;2;2zGGGR&(((T0(0(0(0(0(rrSc0eZdZdZ d dZdZdZdZdS) 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. r5NFcd|vrtj|}tj||||||d\|_|_|dS)Nr7r )r?r?)r9r:rrrdevino _statstreamrs rrzWatchedFileHandler.__init__sq d??'11H$$T8$.6e,2 % 4 4 4$$( rc|jrRtj|j}|t|t c|_|_dSdSN)r@r'fstatfilenorrrrrsress rrzWatchedFileHandler._statstreamsO ; <8DK..0011D!%ftF| DHdhhh < @g@) rHandlerrhostportaddresssock closeOnError retryTime retryStartretryMax retryFactorrrrs rrzSocketHandler.__init__su   &&&  <DLL $cF|jtj|j|}n}tjtjtj}|| ||jn##t$r| wxYw|S)zr A factory method which allows subclasses to define the precise type of socket they want. Ntimeout) rsocketcreate_connectionrAF_UNIX SOCK_STREAM settimeoutconnectOSErrorrA)rrr#s r makeSocketzSocketHandler.makeSocket7s 9 -dlGLLLFF]6>63EFFF   g & & & t|,,,,      s #A>> Bchtj}|jd}n ||jk}|r ||_d|_dS#t$rW|j |j|_n0|j|jz|_|j|jkr |j|_||jz|_YdSwxYwdS)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) rorrrrr retryPeriodrr)rnowattempts r createSocketzSocketHandler.createSocketHs ikk > !GGdn,G  8 8 OO-- !% 8 8 8>)'+D$$'+'7$:J'JD$'$-77+/=(!$t'7!7 8 8 8s AAB/.B/c|j||jrN |j|dS#t$r$|jd|_YdSwxYwdS)z Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. N)rrsendallrrArrs rsendzSocketHandler.sendds 9        9 ! ! !!!$$$$$ ! ! ! !!!   ! ! !sA*A.-A.cL|j}|r||}t|j}||d<d|d<d|d<|ddt j|d}tj dt|}||zS)z Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. rQNargsexc_infomessager>z>L) rrLdict__dict__ getMessagepoppickledumpsstructpackrO)rreidummydrslens r makePicklezSocketHandler.makePicklews _  (KK''E  ! !$$&&%& *  i LA  {4Q((axrc|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)rrrArrrrs rrzSocketHandler.handleErrorsS   6 6 IOO   DIII O ' 'f 5 5 5 5 5rc ||}||dS#t$r||YdSwxYw)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)rrrs rrzSocketHandler.emitsc %''A IIaLLLLL % % %   V $ $ $ $ $ $ %s*.AAc| |j}|rd|_|tj||dS#|wxYwz$ Closes the socket. N)acquirerrArrreleaserrs rrAzSocketHandler.closesr  9D    O ! !$ ' ' ' LLNNNNNDLLNNNN AA//BN)r>) r.r/r0r1rrrrrrrrAr2rrrrs  2"8888!!!&, 6 6 6 % % %     rrc$eZdZdZdZdZdZdS)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. cLt|||d|_dS)zP Initializes the handler with a specific host address and port. FN)rrrrs rrzDatagramHandler.__init__s* tT4000!rc|j tj}n tj}tj|tj}|S)zu The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). )rrrAF_INET SOCK_DGRAM)rfamilyrs rrzDatagramHandler.makeSockets5 9 ^FF^F M&&"3 4 4rc||j||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)rrsendtorrs rrzDatagramHandler.sends> 9        DL)))))rN)r.r/r0r1rrrr2rrrrsK  """    * * * * *rrc |eZdZdZdZdZdZdZdZdZ 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 d4fd5Z(d6Z)d7Z*d8Z+d9Z,d:Z-d;Z.d 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). rr>rJrtrurvrwrx ) alertcritcriticaldebugemergerrerrorinfonoticepanicwarnwarningauthauthprivconsolecrondaemonftpkernlprmailnewsntpsecurityz solaris-cronsysloguseruucplocal0)local1local2local3local4local5local6local7rrrrr)DEBUGINFOWARNINGERRORCRITICAL localhostNctj|||_||_||_d|_|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. N)rrrrfacilitysocktyperr)rrr:r;s rrzSysLogHandler.__init__PsN   &&&       rc|j}| tj}tjtj||_ |j|||_dS#t $r|j|jtj}tjtj||_ |j|||_YdS#t $r|jwxYwwxYwr)r;rrrrrrAr)rr use_socktypes r_connect_unixsocketz!SysLogHandler._connect_unixsocketes}  !,LmFNLAA   K   ( ( ((DMMM    K     }(!-L - EEDK  ##G,,, ,     !!###  s!AAD:!C%DDcN|j}|j}t|tr0d|_ ||dS#t $rYdSwxYwd|_| tj}|\}}tj ||d|}|st d|D]z}|\}}}} } dx} } tj|||} |tj kr| | n/#t $r"} | } | | Yd} ~ sd} ~ wwxYw| | | |_||_dS)af Try to create a socket and, if it's not a datagram socket, connect it to 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 yet --- the method will be called again when emitting an event, if there is no socket at that point. TFNrz!getaddrinfo returns an empty list) rr; isinstancestr unixsocketr>rrr getaddrinforrrA)rrr;rrressresafproto_sarrexcs rrzSysLogHandler.createSocket}sz,= gs # #! %"DO  ((11111    $DO!, JD$%dD!X>>D CABBB % %-0*HeQ!!d%!=Xu==D6#555 R(((E%%%C' % DK$DMMMs)A AA';C$$ D.D  Dct|tr |j|}t|tr |j|}|dz|zS)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. rt)r@rAfacility_namespriority_names)rr:prioritys rencodePriorityzSysLogHandler.encodePrioritysQ h $ $ 5*84H h $ $ 5*84HA ))rc| |j}|rd|_|tj||dS#|wxYwr)rrrArrrrs rrAzSysLogHandler.closesr  ;D "  O ! !$ ' ' ' LLNNNNNDLLNNNNrc8|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)r levelNames r mapPriorityzSysLogHandler.mapPrioritys $$Y :::rTc^ ||}|jr |j|z}|jr|dz }d||j||jz}|d}|d}||z}|js| |j r{ |j |dS#t$rQ|j ||j|j |YdSwxYw|jtjkr"|j||jdS|j|dS#t($r||YdSwxYw)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)rLident append_nulrOr:rU levelnameencoderrrBrrrAr>rr;rrrrr)rrrQprios rrzSysLogHandler.emits %++f%%Cz 'j3& v D// 040@0@AQ0R0RTTTD;;w''D**W%%C*C; $!!### )*K$$S)))))***K%%''',,T\:::K$$S))))))*&"333 ""3 55555 ##C((((( % % %   V $ $ $ $ $ $ %s7B9F <CAD3/F 2D338F -F F,+F,)1r.r/r0r1 LOG_EMERG LOG_ALERTLOG_CRITLOG_ERR LOG_WARNING LOG_NOTICELOG_INFO LOG_DEBUGLOG_KERNLOG_USERLOG_MAIL LOG_DAEMONLOG_AUTH LOG_SYSLOGLOG_LPRLOG_NEWSLOG_UUCPLOG_CRON LOG_AUTHPRIVLOG_FTPLOG_NTP LOG_SECURITY LOG_CONSOLE LOG_SOLCRON LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7rMrLrRSYSLOG_UDP_PORTrr>rrOrArUrZr[rr2rrrrs$IIHGKJHIHHHJHJGHHHLGGLKKJJJJJJJJ   N                                   ! "  # $#""""""1   N@ L!,_="T*0,%,%,%\ * * *   ;;; EJ&%&%&%&%&%rrc(eZdZdZ ddZdZdZdS) SMTPHandlerzK A handler class which sends an SMTP email for each logging event. N@ctj|t|tt fr|\|_|_n|dc|_|_t|tt fr|\|_|_ nd|_||_ t|tr|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)rrrr@listtuplemailhostmailportusernamepasswordfromaddrrAtoaddrssubjectsecurer)rrrrr credentialsrrs rrzSMTPHandler.__init__s$   &&& hu . . :+3 (DM4==+3T (DM4= kD%= 1 1 !+6 (DM4== DM  gs # # iG    rc|jS)z Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. )rrs r getSubjectzSMTPHandler.getSubject"s |rc  ddl}ddlm}ddl}|j}|s|j}||j||j}|}|j |d<d |j |d<| ||d<|j |d <||||jr^|j7||j|j|||j|j|||dS#t2$r||YdSwxYw) zd Emit a record. Format the record and send it to the specified addressees. rN) EmailMessagerFrom,ToSubjectDate)smtplib email.messager email.utilsr SMTP_PORTSMTPrrrrrrutilsr{ set_contentrLrrehlostarttlsloginr send_messagequitrr)rrrremailrsmtprQs rrzSMTPHandler.emit+s  % NNN 2 2 2 2 2 2    =D )(<< tT\<JJD,..C-CK..CI!__V44C N+//11CK OODKK// 0 0 0} 9;*IIKKK!DM4;//IIKKK 4=$-888   c " " " IIKKKKK % % %   V $ $ $ $ $ $ %sEEFF)NNr)r.r/r0r1rrrr2rrrrsV9<!!!!F%%%%%rrc8eZdZdZd dZdZdZdZdZd 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 .tj| ddl}ddl}||_||_|sttj |jj }tj |d}tj |dd}||_ ||_ |j|||n-#t$r }t!|dddkrYd}~nd}~wwxYw|j|_tj|jtj|jtj|jtj|jtj|ji|_dS#t6$rt9dd|_YdSwxYw)Nrzwin32service.pydwinerrorrvzWThe Python Win32 extensions for NT (service, event logging) appear not to be available.)rrrwin32evtlogutil win32evtlogappname_welur'r(r__file__rdllnamelogtypeAddSourceToRegistryrgetattrEVENTLOG_ERROR_TYPEdeftyper3EVENTLOG_INFORMATION_TYPEr4r5EVENTLOG_WARNING_TYPEr6r7typemap ImportErrorprint)rrrrrrrs rrzNTEventLogHandler.__init__Us  &&&  / / / / / / / /"DL(DJ H'-- (;<<'-- 33',,wqz3FGG"DL"DL  ..wIIII   1j$//14454444  ':DL +"G +"G+"C +"A +"A  DLLL    ? @ @ @DJJJJ s=BE0<CE0 D#C>9E0>DA+E00 FFcdS)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. r>r2rs r getMessageIDzNTEventLogHandler.getMessageIDxs qrcdS)z Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. rr2rs rgetEventCategoryz"NTEventLogHandler.getEventCategorys qrcL|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. )rrSlevelnorrs r getEventTypezNTEventLogHandler.getEventTypes | ===rcV|jr ||}||}||}||}|j|j||||gdS#t$r||YdSwxYwdS)z Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. N) rrrrrL ReportEventrrr)rridcattyperQs rrzNTEventLogHandler.emits : ) )&&v..++F33((00kk&)) &&t|RdSEJJJJJ ) ) )  (((((( ) ) )sA8BB&%B&cDtj|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)rrrArs rrAzNTEventLogHandler.closes  d#####r)Nr) r.r/r0r1rrrrrrAr2rrrrKs~!!!!F > > >)))" $ $ $ $ $rrc0eZdZdZ d dZdZdZdZdS) HTTPHandlerz^ A class which sends records to a web server, using either GET or POST semantics. GETFNc tj||}|dvrt d|s|t d||_||_||_||_||_ ||_ 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) rrrr`rhrurlmethodrrcontext)rrrrrrrs rrzHTTPHandler.__init__s   &&&  ( (9:: : 1'-011 1   & rc|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. )rrs r mapLogRecordzHTTPHandler.mapLogRecords rcddl}|r"|j||j}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) http.clientclientHTTPSConnectionrHTTPConnection)rrrhttp connections r getConnectionzHTTPHandler.getConnectionsQ   :44T4<4PPJJ33D99Jrc< ddl}|j}|||j}|j}|j||}|jdkr(| ddkrd}nd}|d||fzz}| |j|| d}|dkr |d|}|jdkrF| d d | d tt||jrtddl} d |jzd } d| | dz} | d| ||jdkr(||d |dS#t.$r||YdSwxYw)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:%srYzBasic ascii Authorization) urllib.parserrrrparse urlencoderrfind putrequest putheaderrArOrbase64r] b64encodestripdecode endheadersr getresponserr) rrurllibrrTrdataseprFrrs rrzHTTPHandler.emits # %    9D""455A(C<))$*;*;F*C*CDDD{e##HHSMMQ&&CCCFc4[00 LLc * * * #AAvvBQBx{f$$ N?AAA ,c#d))nn=== 0 t//77@@v//2288::AA'JJJ OQ/// LLNNN{f$$t{{7++,,, MMOOOOO % % %   V $ $ $ $ $ $ %sG4G88HH)rFNN)r.r/r0r1rrrrr2rrrrsiKO(   )%)%)%)%)%rrc0eZdZdZdZdZdZdZdZdS)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. c`tj|||_g|_dS)z> Initialize the handler with the buffer size. N)rrrcapacitybuffer)rrs rrzBufferingHandler.__init__s,   &&&   rc<t|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. )rOrrrs r shouldFlushzBufferingHandler.shouldFlushsDK  DM12rc|j|||r|dSdS)z Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. N)rrrrrs rrzBufferingHandler.emit'sK 6"""   F # #  JJLLLLL  rc| |j|dS#|wxYw)zw Override to implement custom flushing behaviour. This version just zaps the buffer to empty. N)rrclearrrs rrzBufferingHandler.flush2sM   K      LLNNNNNDLLNNNNs AAc |tj|dS#tj|wxYw)zp Close the handler. This version just flushes and chains to the parent class' close(). N)rrrrArs rrAzBufferingHandler.close>sL  ( JJLLL O ! !$ ' ' ' ' 'GO ! !$ ' ' ' 's 7!AN) r.r/r0r1rrrrrAr2rrrrsi 333       ( ( ( ( (rrcBeZdZdZejddfdZdZdZdZ dZ 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. NTcft||||_||_||_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)rr flushLeveltarget flushOnClose)rrrrrs rrzMemoryHandler.__init__Os6 !!$111$ (rc\t|j|jkp|j|jkS)zP Check for buffer full or a record at the flushLevel or higher. )rOrrrrrs rrzMemoryHandler.shouldFlushcs.DK  DM144?2 4rc| ||_|dS#|wxYw)z: Set the target handler for this handler. N)rrr)rrs r setTargetzMemoryHandler.setTargetjs@   DK LLNNNNNDLLNNNNs 3A c| |jr=|jD]}|j||j|dS#|wxYw)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)rrrhandlerrrs rrzMemoryHandler.flushts  { $"k//FK&&v.... !!### LLNNNNNDLLNNNNs AA00Bc |jr|| d|_t||dS#|wxYw#| d|_t||w#|wxYwxYw)zi Flush, if appropriately configured, set the target to None and lose the buffer. N)rrrrrrArrs rrAzMemoryHandler.closes    LLNNN "  &&t,,,   LLNNN "  &&t,,,  s.B!A))A?C'!C9C'C$$C') r.r/r0r1rr6rrrrrAr2rrrrIsz -4M$"))))(444"rrc*eZdZdZdZdZdZdZdS) 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. cRtj|||_dS)zA Initialise an instance, using the passed queue. N)rrrqueue)rr s rrzQueueHandler.__init__s%   &&& rc:|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)r  put_nowaitrs renqueuezQueueHandler.enqueues  f%%%%%rc||}tj|}||_||_d|_d|_d|_d|_|S)a Prepare 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. Specifically, it overwrites the record's `msg` and `message` attributes with the merged message (obtained by calling the handler's `format` method), and sets the `args`, `exc_info` and `exc_text` attributes to None. 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)rLcopyrrQrrexc_text stack_inforPs rpreparezQueueHandler.preparesT,kk&!!6""    rc |||dS#t$r||YdSwxYw)zm Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. N)r rrrrs rrzQueueHandler.emitsc  % LLf-- . . . . . % % %   V $ $ $ $ $ $ %s(,AAN)r.r/r0r1rr rrr2rrrrs[&&&B % % % % %rrcLeZdZdZdZdddZdZdZdZd Z d Z d Z d 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_levelc>||_||_d|_||_dS)zW Initialise an instance with the specified queue and handlers. N)r handlers_threadr)rr rrs rrzQueueListener.__init__s'     %:"""rc6|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. )r rS)rblocks rdequeuezQueueListener.dequeuesz~~e$$$rc~tj|jx|_}d|_|dS)z Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. )rTN) threadingThread_monitorrr start)rrrs rr!zQueueListener.starts8%+4=AAAA q  rc|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. r2rs rrzQueueListener.prepares  rc||}|jD]3}|jsd}n|j|jk}|r||4dS)z| Handle a record. This just loops through the handlers offering them the record to handle. TN)rrrrlevelr)rrhandlerprocesss rrzQueueListener.handleskf%%} ' 'G- : .GM9 'v&&&  ' 'rc&|j}t|d} |d}||jur|r|dS|||r|n#tj$rYdSwxYwz)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)r hasattrr _sentinelr(rEmpty)rq has_task_doners rr zQueueListener._monitors J;//   d++T^++$& E F### "KKMMM;     s4A<+A<<BBcD|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)r r r*rs renqueue_sentinelzQueueListener.enqueue_sentinel6s" dn-----rcn||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)r/rrrs rstopzQueueListener.stop@s5   r) r.r/r0r1r*rrr!rrr r/r1r2rrrrs I?D;;;;;%%%   ''' ....     rr)(r1r9rrr'rrrorkrnrrrr rrDEFAULT_TCP_LOGGING_PORTDEFAULT_UDP_LOGGING_PORTDEFAULT_HTTP_LOGGING_PORTDEFAULT_SOAP_LOGGING_PORTrSYSLOG_TCP_PORTr|rrr4rSrrrrrrrrrrrobjectrr2rrr8s"98888888888888888888888888888888))))))))))  #"""!!  H'H'H'H'H''-H'H'H'TQQQQQ-QQQf{({({({({(2{({({(zG/G/G/G/G/,G/G/G/TeeeeeGOeeeN(*(*(*(*(*m(*(*(*TW%W%W%W%W%GOW%W%W%rN%N%N%N%N%'/N%N%N%`i$i$i$i$i$i$i$i$VX%X%X%X%X%'/X%X%X%t7(7(7(7(7(w7(7(7(rJJJJJ$JJJZF%F%F%F%F%7?F%F%F%RkkkkkFkkkkkr