QfxdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl Z ddlZddlZdZdZdZdZdZdZd ZGd d ej.ZGd d eZGddeZGddej.ZGddej8ZGddeZGddej8ZGddej8Z Gddej8Z!Gddej8Z"Gddej8Z#Gd d!e#Z$Gd"d#ej8Z%Gd$d%e&Z'y)&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?#iQc2eZdZdZdZdZddZdZdZdZ y)BaseRotatingHandlerz Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. Ncxtjj||||||||_||_||_y)zA Use the specified filename for streamed logging modeencodingdelayerrorsN)logging FileHandler__init__r r rselffilenamer r r rs 7/opt/alt/python312/lib64/python3.12/logging/handlers.pyrzBaseRotatingHandler.__init__6sB $$T8$.6e,2 % 4    c |j|r|jtjj ||y#t $r|j |YywxYw)z Emit a record. Output the record to the file, catering for rollover as described in doRollover(). N)shouldRollover doRolloverrremit Exception handleErrorrrecords rrzBaseRotatingHandler.emitAsR %""6*!    $ $T6 2 %   V $ %sAAA! A!cZt|js|}|S|j|}|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_filenameOs1 #!F ZZ -F rct|js7tjj |rtj ||yy|j||y)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.rotatebsC %ww~~f% &$'& LL &r)NFN) __name__ __module__ __qualname____doc__r!r&rrr$r-rrrr-s' EG  %&'rrc(eZdZdZ ddZdZdZy)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. Nc|dkDrd}d|vrtj|}tj||||||||_||_y)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. rabr r rN)io text_encodingrrmaxBytes backupCount)rrr r;r<r r rs rrzRotatingFileHandler.__init__|sW6 a<D d?''1H$$T8TH+0 % A  &rc6|jr!|jjd|_|jdkDr:t|jdz ddD]}|j d|j |fz}|j d|j |dzfz}t jj|sft jj|rt j|t j|||j |j dz}t jj|rt j||j|j ||js|j|_yy)z< Do a rollover, as described in __init__(). Nrz%s.%dz.1)streamcloser<ranger$ baseFilenamer'r(r)remover*r-r _open)risfndfns rrzRotatingFileHandler.doRollovers8 ;; KK   DK   a 4++a/B7,,W8I8I17M-MN,,W8I8I89A8?.?@77>>#&ww~~c* #IIc3'8(():):T)ABCww~~c" # KK))3 /zz**,DKrc|j|j|_|jdkDr|jj}|syd|j |z}|t |z|jk\rTt jj|jr*t jj|jsyyy)z Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. rFz%s T) r@rEr;tellformatlenr'r(r)rCisfile)rrposmsgs rrz"RotatingFileHandler.shouldRollovers ;; **,DK ==1 ++""$C4;;v..CSX~.77>>$"3"34RWW^^DL]L]=^ r)r6rrNFN)r.r/r0r1rrrr2rrr4r4ws!DE48"'H'.rr4c6eZdZdZ ddZdZdZdZdZy) 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. Nc tj|}tj||d||| |j |_||_||_||_|j dk(rd|_ d|_ d} n=|j dk(rd|_ d |_ d } n|j d k(rd |_ d |_ d} n|j dk(s|j dk(rd|_ d|_ d} n|j jdrd|_ t|j dk7rtd|j z|j ddks|j ddkDrtd|j zt|j d|_d|_ d} ntd|j zt!j"| t j$|_|j|z|_ |j(}t*j,j/|rt+j0|t2} ntt5j4} |j7| |_y)Nr6r8Sr>z%Y-%m-%d_%H-%M-%Sz0(?H YY# j!8(DM$DK8H YY ! !# &,DM499~" !knrnwnw!wxxyy|c!TYYq\C%7 !PSWS\S\!\]] 1.DN$DK8HFRS S 8RXX6  0 $$ 77>>( #!(+ADIIK A..q1rc||jz}|jdk(s|jjdr|jrt j |}nt j |}|d}|d}|d}|d}|jt}nJ|jjdz|jjzdz|jjz}||dz|zdz|zz } | dkr| tz } |d zd z}|| z}|jjdrk|} | |jk7r@| |jkr|j| z } nd| z |jzd z} || tzz }||jtd zz z }n||jtz z }|jsK|d } t j |d } | | k7r)| s d }t j |d z d sd}nd }||z }|S)zI Work out the rollover time based on the specified time. rYrZrUrr>r?rW) rbr_rdr`rmgmtime localtimera _MIDNIGHThourminutesecondrg)r currentTimer#rp currentHour currentMinute currentSecond currentDay rotate_tsrday daysToWaitdstNow dstAtRolloveraddends rrnz(TimedRotatingFileHandler.computeRolloverst}}, 99 "dii&:&:3&?xxKK ,NN;/A$KaDMaDM1J{{"% "kk..3dkk6H6HH"LKK&&' kB.>"DAAvY(1n1  1_F yy##C( $..(T^^+%)^^c%9 %&Wt~~%=%A j944F$--)a-77$--)33882 $v 6r : ]*!!&#~~fTk:2>%&F!%f$F rc0ttj}||jk\rjtjj |j r@tjj|j s|j||_yyy)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) rfrmror'r(r)rCrMrn)rrrps rrz'TimedRotatingFileHandler.shouldRolloveresh    ww~~d//0HYHY9Z#'"6"6q"9rctjj|j\}}tj|}g}|j q|dz}t |}|D][}|d||k(s ||d}|jj|s-|jtjj||]n|D]}|jj|} | s!|j |jdz| dz} tjj| |k(r0|jtjj|||jj|| jdz} | rt ||jkrg}|S|j|dt ||jz }|S)z Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). N.rr>)r'r(splitrClistdirr!rLrk fullmatchappendjoinsearchbasenamestartr<sort) rdirNamebaseName fileNamesr#prefixplenfileNamercmrHs rgetFilesToDeletez)TimedRotatingFileHandler.getFilesToDeletexs GGMM$*;*;<JJw'  :: ^Fv;D%ET?f,%de_F}}..v6 bggll7H&EF & & MM((2**T%6%6%>#   ;; KK   DK D%%s+   a **, ! -zz**,DK..{;r)hr>rNFFNN) r.r/r0r1rrnrrrr2rrrQrQs2DE?CA2FKZ&$L&> C  C cd|jtjj||y)z Emit a record. If underlying file has changed, reopen the file before emitting the record to it. N)rrrrrs rrzWatchedFileHandler.emits&   v.r)r6NFN)r.r/r0r1rrrrr2rrrrs%&AF< #8/rrcBeZdZdZdZd dZdZdZdZdZ dZ d Z y ) 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. ctjj|||_||_|||_n ||f|_d|_d|_d|_d|_ d|_ d|_ y)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@) rHandlerrhostportaddresssock closeOnError retryTime retryStartretryMax retryFactorrrrs rrzSocketHandler.__init__si   &  <DL $>63E3EFF   g & t||,    s 4BB,ctj}|jd}n||jk\}|r |j|_d|_yy#t$r}|j|j |_nH|j |jz|_|j |jkDr|j|_||j z|_YywxYw)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) rmrrrrr retryPeriodrr)rnowattempts r createSocketzSocketHandler.createSocketGs iik >> !Gdnn,G  8 OO- !%  8>>)'+D$'+'7'7$:J:J'JD$''$--7+/==(!$t'7'7!7 8sABCCc|j|j|jr |jj|yy#t$r$|jj d|_YywxYw)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.sendcse 99      99 ! !!!$  ! !   !sA*A43A4c<|j}|r|j|}t|j}|j |d<d|d<d|d<|j ddt j|d}tjdt|}||zS)z Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. rONargsexc_infomessager>z>L) rrKdict__dict__ getMessagepoppickledumpsstructpackrL)rreidummydrslens r makePicklezSocketHandler.makePicklevs __ KK'E  !$$&%& *  i LLA {{4Q(axrc|jr.|jr"|jjd|_ytjj ||y)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.handleErrors<    IIOO DI OO ' 'f 5rc |j|}|j|y#t$r|j|YywxYw)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.emits= %'A IIaL %   V $ %s"%AAc|j |j}|rd|_|jtjj||j y#|j wxYwz$ Closes the socket. N)acquirerrArrreleaserrs rrAzSocketHandler.closesS  99D   OO ! !$ ' LLNDLLN AA''A9N)r>) r.r/r0r1rrrrrrrrAr2rrrrs/ 2"88!&, 6 % rrc"eZdZdZdZdZdZy)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. c@tj|||d|_y)zP Initializes the handler with a specific host address and port. FN)rrrrs rrzDatagramHandler.__init__s tT40!rc|jtj}ntj}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.makeSockets; 99 ^^F^^F MM&&"3"3 4rc|j|j|jj||jy)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.sends2 99      DLL)rN)r.r/r0r1rrrr2rrrrs "  *rrc zeZdZdZdZdZdZdZdZdZ 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>r[rrrsrtrurv ) alertcritcriticaldebugemergerrerrorinfonoticepanicwarnwarningauthauthprivconsolecrondaemonftpkernlprmailnewsntpsecurityz solaris-cronsysloguseruucplocal0)local1local2local3local4local5local6local7rrrrr )DEBUGINFOWARNINGERRORCRITICAL localhostNctjj|||_||_||_d|_|jy)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)rrr5r6s rrzSysLogHandler.__init__Ms>   &       rcL|j}|tj}tjtj||_ |jj |||_y#t $r|jj |jtj}tjtj||_ |jj |||_Yy#t $r|jj wxYwwxYwr)r6rrrrrrAr)rr use_socktypes r_connect_unixsocketz!SysLogHandler._connect_unixsocketbs}}  !,,LmmFNNLA   KK   ((DM  KK   }}(!--L -- EDK  ##G, ,   !!#  s "A,,A)D#"C::%DD#cD|j}|j}t|trd|_ |j |yd|_|tj}|\}}tj||d|}|s t d|D]K}|\}}}} } dx} } tj|||} |tjk(r| j| n |  |_||_y#t $rYywxYw#t $r} | } | | jYd} ~ d} ~ wwxYw)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) rr6 isinstancestr unixsocketr9rrr getaddrinforrrA)rrr6rrressresafproto_sarrexcs rrzSysLogHandler.createSocketzs.,,== gs #"DO  ((1$DO!,, JD$%%dD!X>DABB-0*HeQ!!d%!==Xu=D6#5#55 R( DK$DM3  $%C' %s)C);C8) C54C58 DDDct|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. rr)r;r<facility_namespriority_names)rr5prioritys rencodePriorityzSysLogHandler.encodePrioritysG h $**84H h $**84HA ))rc|j |j}|rd|_|jtjj||j y#|j wxYwr)rrrArrrrs rrAzSysLogHandler.closesS  ;;D"  OO ! !$ ' LLNDLLNrc:|jj|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 |j|}|jr|j|z}|jr|dz }d|j|j|j |j z}|jd}|jd}||z}|js|j|jr |jj|y|j tj"k(r'|jj%||jy|jj'|y#t$rS|jj|j|j|jj|YywxYw#t($r|j+|YywxYw)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)rKident append_nulrJr5rP levelnameencoderrr=rrrAr9rr6rrrrr)rrrOprios rrzSysLogHandler.emitsf %++f%Czzjj3&v D// 040@0@AQAQ0RTTD;;w'D**W%C*C;;!!#*KK$$S) &"3"33 ""3 5 ##C(*KK%%',,T\\:KK$$S)* %   V $ %s>CF"E#AF"'F"AFF"FF""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_LOCAL7rHrGrMSYSLOG_UDP_PORTrr9rrJrArPrUrVrr2rrrrs$IIHGKJHIHHHJHJGHHHLGGLKKJJJJJJJJ  N                                   ! "  # $#""""""1 N< L!,_="T*0,%\ * ; EJ&%rrc&eZdZdZ ddZdZdZy) SMTPHandlerzK A handler class which sends an SMTP email for each logging event. Ncrtjj|t|tt fr|\|_|_n|dc|_|_t|tt fr|\|_|_ nd|_||_ t|tr|g}||_ ||_ ||_||_y)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;listtuplemailhostmailportusernamepasswordfromaddrr<toaddrssubjectsecurer)rrrrr credentialsrrs rrzSMTPHandler.__init__s$   & hu .+3 (DM4=+3T (DM4= kD%= 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.getSubjects||rc  ddl}ddlm}ddl}|j}|s |j }|j |j||j}|}|j|d<dj|j|d<|j||d<|jj|d <|j|j!||j"rk|j$9|j'|j(|j$|j'|j+|j"|j,|j/||j1y#t2$r|j5|YywxYw) zd Emit a record. Format the record and send it to the specified addressees. rN) EmailMessagerFrom,ToSubjectDate)smtplib email.messager email.utilsr SMTP_PORTSMTPrrrrrrutilsry set_contentrKrrehlostarttlsloginr send_messagequitrr)rrrremailrsmtprOs rrzSMTPHandler.emit(s)  %  2 ==D((<< tT\\<JD.C--CK.CI!__V4C N++//1CK OODKK/ 0}};;*IIK!DMM4;;/IIK 4==$--8   c " IIK %   V $ %sE-E00F  F )NNg@)r.r/r0r1rrrr2rrr|r|s9<!F%rr|c6eZdZdZd dZdZdZdZdZdZ y) 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. Nc tjj| ddl}ddl}||_||_|sxtjj|j j}tjj|d}tjj|dd}||_ ||_ |j j||||j"|_tj&|j(tj*|j(tj,|j.tj0|j"tj2|j"i|_y#t$r}t!|dddk7rYd}~d}~wwxYw#t6$rt9dd|_YywxYw)Nrzwin32service.pydwinerrorrtzWThe Python Win32 extensions for NT (service, event logging) appear not to be available.)rrrwin32evtlogutil win32evtlogappname_welur'r(r__file__rdllnamelogtypeAddSourceToRegistryrgetattrEVENTLOG_ERROR_TYPEdeftyper.EVENTLOG_INFORMATION_TYPEr/r0EVENTLOG_WARNING_TYPEr1r2typemap ImportErrorprint)rrrrrres rrzNTEventLogHandler.__init__RsX  &  /"DL(DJ''-- (;(;<''-- 3'',,wqz3FG"DL"DL  ..wI '::DL +"G"G +"G"G+"C"C +"A"A  +"A"A  DL  1j$/145   ? @DJ s=BFE8BF8 FFFFFF=<F=cy)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.getMessageIDusrcy)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.getEventCategorysrcb|jj|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. )rrNlevelnorrs r getEventTypezNTEventLogHandler.getEventTypes#|| ==rc<|jrp |j|}|j|}|j|}|j |}|jj |j ||||gyy#t$r|j|YywxYw)z Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. N) rrrrrK ReportEventrrr)rridcattyperOs rrzNTEventLogHandler.emits :: )&&v.++F3((0kk&) &&t||RdSEJ  )  ( )sA.A>>BBcBtjj|y)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)N Application) r.r/r0r1rrrrrrAr2rrrrHs&!F >)" $rrc.eZdZdZ ddZdZdZdZy) HTTPHandlerz^ A class which sends records to a web server, using either GET or POST semantics. Nctjj||j}|dvr t d|s | t d||_||_||_||_||_ ||_ y)zr Initialize the instance with the host, the request URL, and the method ("GET" or "POST") )GETPOSTzmethod must be GET or POSTNz3context parameter only makes sense with secure=True) rrrr^rerurlmethodrrcontext)rrrrrrrs rrzHTTPHandler.__init__sz   &  (9: :'-01 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)|jj||j}|S|jj |}|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.getConnectionsK  44T4<<4PJ33D9Jrc ddl}|j}|j||j}|j}|j j |j|}|jdk(r#|jddk\rd}nd}|d||fzz}|j|j||jd}|dk\r|d|}|jdk(r6|jd d |jd tt||jreddl} d |jzj!d } d| j#| j%j'dz} |jd| |j)|jdk(r |j+|j!d |j-y#t.$r|j1|YywxYw)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:%srTzBasic ascii Authorization) urllib.parserrrrparse urlencoderrfind putrequest putheaderr<rLrbase64rX b64encodestripdecode endheadersr getresponserr) rrurllibrrrdataseprFrrs rrzHTTPHandler.emits # % 99D""45A((C<<))$*;*;F*CDD{{e#HHSMQ&CCFc4[00 LLc * #AAvBQx{{f$ N?A ,c#d)n=t///77@v//288:AA'JJ OQ/ LLN{{f$t{{7+, MMO %   V $ %sGGG0/G0)rFNN)r.r/r0r1rrrrr2rrrrs%KO( )%rrc.eZdZdZdZdZdZdZdZy)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^tjj|||_g|_y)z> Initialize the handler with the buffer size. N)rrrcapacitybuffer)rrs rrzBufferingHandler.__init__s$   &   rcFt|j|jk\S)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. )rLrrrs r shouldFlushzBufferingHandler.shouldFlushsDKK DMM12rc~|jj||j|r|jyy)z Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. N)rrrrrs rrzBufferingHandler.emit$s2 6"   F # JJL $rc|j |jj|jy#|jwxYw)zw Override to implement custom flushing behaviour. This version just zaps the buffer to empty. N)rrclearrrs rrzBufferingHandler.flush/s5   KK    LLNDLLNs =Ac |jtjj|y#tjj|wxYw)zp Close the handler. This version just flushes and chains to the parent class' close(). N)rrrrArs rrAzBufferingHandler.close;s5  ( JJL OO ! !$ 'GOO ! !$ 's 2!AN) r.r/r0r1rrrrrAr2rrrr s  3   (rrcJeZdZdZej ddfdZdZdZdZ dZ y) 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. NTcZtj||||_||_||_y)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__Ls* !!$1$ (rc|t|j|jk\xs|j|jk\S)zP Check for buffer full or a record at the flushLevel or higher. )rLrrrrrs rrzMemoryHandler.shouldFlush`s3DKK DMM144??2 4rc~|j ||_|jy#|jwxYw)z: Set the target handler for this handler. N)rrr)rrs r setTargetzMemoryHandler.setTargetgs,   DK LLNDLLNs*<c|j |jrF|jD]}|jj||jj |j y#|j 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 only cleared if a target has been set. N)rrrhandlerrrs rrzMemoryHandler.flushqs\  {{"kkFKK&&v.* !!# LLNDLLNs AA55Bc |jr|j|j d|_tj ||j y#|j wxYw#|j d|_tj ||j w#|j wxYwxYw)zi Flush, if appropriately configured, set the target to None and lose the buffer. N)rrrrrrArrs rrAzMemoryHandler.closes    LLN "  &&t,   LLN "  &&t,  s.A1AA.1CB0C0CC) r.r/r0r1rr1rrrrrAr2rrrrFs. -4MM$")(4"rrc(eZdZdZdZdZdZdZy) 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. c^tjj|||_d|_y)zA Initialise an instance, using the passed queue. N)rrrqueuelistener)rrs rrzQueueHandler.__init__s$   &  rc:|jj|y)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|j|}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)rKcopyrrOrrexc_text stack_info)rrrOs rpreparezQueueHandler.preparesP,kk&!6"    rc |j|j|y#t$r|j|YywxYw)zm Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. N)r rrrrs rrzQueueHandler.emits9  % LLf- . %   V $ %s #AAN)r.r/r0r1rr rrr2rrrrs&B %rrcJeZdZdZdZdddZdZdZdZd Z d Z d Z d Z y) 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|_||_y)zW Initialise an instance with the specified queue and handlers. N)rhandlers_threadr)rrrrs rrzQueueListener.__init__s!     %:"rc8|jj|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. )rrN)rblocks rdequeuezQueueListener.dequeueszz~~e$$rctj|jx|_}d|_|j y)z Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. )rTN) threadingThread_monitorrrr)rrps rrzQueueListener.starts/%++4==AA 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|j|}|jD]>}|jsd}n|j|jk\}|s.|j |@y)z| Handle a record. This just loops through the handlers offering them the record to handle. TN)rrrrlevelr)rrhandlerprocesss rrzQueueListener.handle sOf%}}G-- ..GMM9v& %rc|j}t|d} |jd}||jur|r|j y|j ||r|j W#tj $rYywxYw)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)rhasattrr _sentinelr#rEmpty)rq has_task_doners rrzQueueListener._monitors JJ;/  d+T^^+$  F# KKM;;  s1A1 #A11BBcN|jj|jy)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)rrr%rs renqueue_sentinelzQueueListener.enqueue_sentinel4s dnn-rcf|j|jjd|_y)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>s'   r) r.r/r0r1r%rrrrrrr*r,r2rrrrs9 I?D;% ' .. rr)(r1r9rrr'rrrmrhrlrrrrrr DEFAULT_TCP_LOGGING_PORTDEFAULT_UDP_LOGGING_PORTDEFAULT_HTTP_LOGGING_PORTDEFAULT_SOAP_LOGGING_PORTrzSYSLOG_TCP_PORTrzrrr4rQrrrrrr|rrrrrobjectrr2rrr3sH"9888))  #"""!!  H''--H'TT-Tlw<2w