Ϫf4\dZddlmZddlmZddlmZmZmZm Z m Z m Z m Z ddl mZddlmZddlmZddlmZd d lmZmZd d lmZd Zdd ZddZedf d dZef d!dZd"dZGdde Z!Gdde e"efZ#d#dZ$ddZ%d$dZ&ddZ'dddef d%dZ(y)&z& Tools for formatting logging events. ) annotations)datetime)AnyCallableIteratorMappingOptionalUnioncast) NamedConstant)FixedOffsetTimeZone)Failure) safe_repr) aFormatter flatFormat)LogEventz%Y-%m-%dT%H:%M:%S%zc t|dddS)aa Formats an event as text, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string. F)includeTracebackincludeTimestamp includeSystem) eventAsText)events 8/usr/lib/python3/dist-packages/twisted/logger/_format.py formatEventrs    c dj||S#t$rPt}djd|j D}djt |||cYSwxYw)z Formats an event as text that describes the event generically and a formatting error. @param event: A logging event. @param error: The formatting error. @return: A formatted string. z)Unable to format event {event!r}: {error})rerrorz, c3lK|],\}}djt|t|f.yw)z = N)joinr).0keyvalues r z+formatUnformattableEvent..Cs3 U JJ # %(89 : s24zrMESSAGE LOST: unformattable object logged: {error} Recoverable data: {text} Exception during formatting: {failure})rfailuretext)format BaseExceptionrr itemsr)rrr%r&s rformatUnformattableEventr*-s :AAuB    )yy #kkm    66>> from time import time >>> from twisted.logger import formatTime >>> >>> t = time() >>> formatTime(t) u'2013-10-22T14:19:11-0700' >>> formatTime(t, timeFormat="%Y/%W") # Year and week number u'2013/42' >>> @param when: A timestamp. @param timeFormat: A time format. @param default: Text to return if C{when} or C{timeFormat} is L{None}. @return: A formatted time. )r fromLocalTimeStampDateTime fromtimestampstrstrftime)when timeFormatdefaulttzrs r formatTimer6QsK4T\ 3 3D 9))$38$$Z011rcPt||}|sy|jdd}|dzS)a& Format an event as a line of human-readable text for, e.g. traditional log file output. The output format is C{"{timeStamp} [{system}] {event}\n"}, where: - C{timeStamp} is computed by calling the given C{formatTime} callable on the event's C{"log_time"} value - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. Example:: >>> from time import time >>> from twisted.logger import formatEventAsClassicLogText >>> from twisted.logger import LogLevel >>> >>> formatEventAsClassicLogText(dict()) # No format, returns None >>> formatEventAsClassicLogText(dict(log_format="Hello!")) u'- [-#-] Hello!\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_namespace="my_namespace", ... log_level=LogLevel.info, ... )) u'2013-10-22T17:30:02-0700 [my_namespace#info] Hello!\n' >>> formatEventAsClassicLogText(dict( ... log_format="Hello!", ... log_time=time(), ... log_system="my_system", ... )) u'2013-11-11T17:22:06-0800 [my_system] Hello!\n' >>> @param event: an event. @param formatTime: A time formatter @return: A formatted event, or L{None} if no output is appropriate. )r6N z )rreplace)rr6 eventTexts rformatEventAsClassicLogTextr;ss4^Ej9I !!$/I t rPotentialCallWrappercn|jd}|r|ddn|}||}|r|}t|S)at Check to see if C{key} ends with parentheses ("C{()}"); if not, wrap up the result of C{get} in a L{PotentialCallWrapper}. Otherwise, call the result of C{get} first, before wrapping it up. @param key: The last dotted segment of a formatting key, as parsed by L{Formatter.vformat}, which may end in C{()}. @param getter: A function which takes a string and returns some other object, to be formatted and stringified for a log. @return: A L{PotentialCallWrapper} that will wrap up the result to allow for subsequent usages of parens to defer execution to log-format time. z()N)endswithr<)r"gettercallitrealKeyr#s rkeycallrCs?\\$ F c#2hcG 7OE   &&rc@eZdZdZd dZd dZd dZd dZd dZd dZ y) r<z Object wrapper that wraps C{getattr()} so as to process call-parentheses C{"()"} after a dotted attribute access. c||_yN)_wrapped)selfwrappeds r__init__zPotentialCallWrapper.__init__s  rcBt||jjSrF)rCrG__getattribute__)rHnames r __getattr__z PotentialCallWrapper.__getattr__stT]];;<>> formatWithCall("{string}, {function()}.", ... dict(string="just a string", ... function=lambda: "a function")) 'just a string, a function.' @param formatString: A PEP-3101 format string. @param mapping: A L{dict}-like object to format. @return: The string with formatted values interpolated. r`)r0rvformatrb) formatStringmappings rformatWithCallrss#. z!!,K4HI JJrcn d|vr t|Sttttt f|j dd}|yt|trn0t|t r|jd}ntd|t||S#t$r}t||cYd}~Sd}~wwxYw)ae Formats an event as a string, using the format in C{event["log_format"]}. This implementation should never raise an exception; if the formatting cannot be done, the returned string will describe the event generically so that a useful message is emitted regardless. @param event: A logging event. @return: A formatted string. log_flattened log_formatNzutf-8zLog format must be str, not ) rr r r r0bytesget isinstancedecode TypeErrorrsr(r*)rr'es r _formatEventr~s2 e #e$ $huS%Z01599\43PQ > fc "   &]]7+F:6*EF Ffe,, 2'q112s)B6BA B B4 B/)B4/B4cr |j}|S#t$r}dt|z}Yd}~|Sd}~wwxYw)a^ Format a failure traceback, assuming UTF-8 and using a replacement strategy for errors. Every effort is made to provide a usable traceback, but should not that not be possible, a message and the captured exception are logged. @param failure: The failure to retrieve a traceback from. @return: The formatted traceback. z((UNABLE TO OBTAIN TRACEBACK FROM EVENT):N) getTracebackr(r0)r% tracebackr}s r_formatTracebackr5sFH((*   H>QG Hs 616c jttt|jdd}|kttt|jdd}|d}n |j }dj tt|jdd|}|S t|}|S#t$rd}Y|SwxYw) a Format the system specified in the event in the "log_system" key if set, otherwise the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. If formatting fails completely, "UNFORMATTABLE" is returned. @param event: The event containing the system specification. @return: A formatted string representing the "log_system" key. log_systemN log_levelr+z{namespace}#{level} log_namespace) namespacelevel UNFORMATTABLE)r r r0ryr rMr' Exception)rsystemr levelNames r _formatSystemrGs(3-<!> ?F ~Xm,eii T.JK =I I&--3 /3 ?@.  M  %[F M %$F M %s B## B21B2Tc Tt|}|r'd|vr#|d}t|}dj||f}|s|Sd}|r7dj|tt|j dddg}d} |rdjdt |ddg} d j|| | S) ah Format an event as text. Optionally, attach timestamp, traceback, and system information. The full output format is: C{"{timeStamp} [{system}] {event}\n{traceback}\n"} where: - C{timeStamp} is the event's C{"log_time"} value formatted with the provided C{formatTime} callable. - C{system} is the event's C{"log_system"} value, if set, otherwise, the C{"log_namespace"} and C{"log_level"}, joined by a C{"#"}. Each defaults to C{"-"} is not set. - C{event} is the event, as formatted by L{formatEvent}. - C{traceback} is the traceback if the event contains a C{"log_failure"} key. In the event the original traceback cannot be formatted, a message indicating the failure will be substituted. If the event cannot be formatted, and no traceback exists, an empty string is returned, even if includeSystem or includeTimestamp are true. @param event: A logging event. @param includeTraceback: If true and a C{"log_failure"} key exists, append a traceback. @param includeTimestamp: If true include a formatted timestamp before the event. @param includeSystem: If true, include the event's C{"log_system"} value. @param formatTime: A time formatter @return: A formatted string with specified options. @since: Twisted 18.9.0 log_failurer8rwlog_timeN []z{timeStamp}{system}{eventText}) timeStamprr:)r~rr r floatryrr') rrrrr6r:frrrs rrrfsTU#IMU2 - $Q' IIy)45 IGGZUEIIj$4O(PQSVWX F#}U3S#>? + 2 2 3 rN)rrrZr0)rrrr(rZr0)r2zOptional[float]r3 Optional[str]r4r0rZr0)rrr6z Callable[[Optional[float]], str]rZr)r"r0r@zCallable[[str], Any]rZr<)rqr0rrrmrZr0)r%rrZr0) rrrboolrrrrr6zCallable[[float], str]rZr0))r_ __future__rrr.typingrrrrr r r constantlyr twisted.python._tzhelperr twisted.python.failurertwisted.python.reflectr_flattenrr _interfacesrtimeFormatRFC3339rr*r6r;rCrYr<r0rbrsr~rrrr`rrrs #)JJJ$8*,,!)(! L!22 222 2FEO3 3!A33l'.'6'8:'#s(#::K42D$B"!)3 ? ??? ? ' ?  ?r