Ë
    oj¨4  ã                  ó\  — d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
mZmZ ddlmZ ddlmZ ddlmZ ddlmZ d	d
lmZmZ d	dlmZ dZdd„Zdd„Zedf	 	 	 	 	 	 	 d d„Zef	 	 	 	 	 d!d„Zd"d„Z G d„ de «      Z! G d„ de	e"ef   «      Z#d#d„Z$dd„Z%d$d„Z&dd„Z'dddef	 	 	 	 	 	 	 	 	 	 	 d%d„Z(y)&z&
Tools for formatting logging events.
é    )Úannotations)Údatetime)ÚAnyÚCallableÚIteratorÚMappingÚOptionalÚUnionÚcast)ÚNamedConstant)ÚFixedOffsetTimeZone)ÚFailure)Ú	safe_repré   )Ú
aFormatterÚ
flatFormat)ÚLogEventz%Y-%m-%dT%H:%M:%S%zc                ó    — t        | ddd¬«      S )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)ÚincludeTracebackÚincludeTimestampÚincludeSystem)ÚeventAsText)Úevents    ú8/usr/lib/python3/dist-packages/twisted/logger/_format.pyÚformatEventr      s   € ô ØØØØô	ð ó    c                óâ   — 	 dj                  | |¬«      S # t        $ rP t        «       }dj                  d„ | j	                  «       D «       «      }dj                  t        |«      ||¬«      cY S w xY w)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})r   Úerrorz, c              3  ól   K  — | ],  \  }}d j                  t        |«      t        |«      f«      –— Œ. y­w)z = N)Újoinr   )Ú.0ÚkeyÚvalues      r   ú	<genexpr>z+formatUnformattableEvent.<locals>.<genexpr>C   s3   è ø€ ò 
á��Uð �J‰Jœ	 #›¬	°%Ó(8Ð9×:ñ
ùs   ‚24zrMESSAGE LOST: unformattable object logged: {error}
Recoverable data: {text}
Exception during formatting:
{failure})r   ÚfailureÚtext)ÚformatÚBaseExceptionr   r    Úitemsr   )r   r   r%   r&   s       r   ÚformatUnformattableEventr*   -   s…   € ð
Ø:×AÑAØ˜uð Bó 
ð 	
øô ò 
ô “)ˆà�y‰yñ 
à#Ÿk™k›mô
ó 
ˆð6ç6<±fÜ Ó&°¸dð 7=ó 7ò	
ð
ús   ‚ •AA.Á-A.ú-c                ó˜   — |�| €|S t        j                  | «      }t        j                  | |«      }t	        |j                  |«      «      S )aÿ  
    Format a timestamp as text.

    Example::

        >>> 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   ÚfromLocalTimeStampÚDateTimeÚfromtimestampÚstrÚstrftime)ÚwhenÚ
timeFormatÚdefaultÚtzr   s        r   Ú
formatTimer6   Q   sK   € ð4 Ð˜T˜\Øˆä ×3Ñ3°DÓ9ˆÜ×)Ñ)¨$°Ó3ˆÜ�8×$Ñ$ ZÓ0Ó1Ð1r   c                óP   — t        | |¬«      }|sy|j                  dd«      }|dz   S )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.
    )r6   Nú
z
	)r   Úreplace)r   r6   Ú	eventTexts      r   ÚformatEventAsClassicLogTextr;   s   s4   € ô^ ˜E¨jÔ9€IÙØØ×!Ñ! $¨Ó/€IØ�tÑÐr   ÚPotentialCallWrapperc                ón   — | j                  d«      }|r| dd n| } ||«      }|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"   ÚgetterÚcallitÚrealKeyr#   s        r   ÚkeycallrC   ©   s?   € ð �\‰\˜$Ó€FÙ ˆc�#�2‰h c€GÙ�7‹O€EÙÙ“ˆÜ Ó&Ð&r   c                  ó@   — e Zd ZdZd	d„Zd
d„Zd
d„Zdd„Zdd„Zdd„Z	y)r<   z
    Object wrapper that wraps C{getattr()} so as to process call-parentheses
    C{"()"} after a dotted attribute access.
    c                ó   — || _         y ©N)Ú_wrapped)ÚselfÚwrappeds     r   Ú__init__zPotentialCallWrapper.__init__Æ   s	   € Øˆ�r   c                óB   — t        || j                  j                  «      S rF   )rC   rG   Ú__getattribute__)rH   Únames     r   Ú__getattr__z PotentialCallWrapper.__getattr__É   s   € Ü�t˜TŸ]™]×;Ñ;Ó<Ð<r   c                ó6   — | j                   |   }t        |«      S rF   )rG   r<   )rH   rM   r#   s      r   Ú__getitem__z PotentialCallWrapper.__getitem__Ì   s   € ð —‘˜dÑ#ˆÜ# EÓ*Ð*r   c                ó8   — | j                   j                  |«      S rF   )rG   Ú
__format__)rH   Úformat_specs     r   rR   zPotentialCallWrapper.__format__Ò   s   € Ø�}‰}×'Ñ'¨Ó4Ð4r   c                ó6   — | j                   j                  «       S rF   )rG   Ú__repr__©rH   s    r   rU   zPotentialCallWrapper.__repr__Õ   s   € Ø�}‰}×%Ñ%Ó'Ð'r   c                ó6   — | j                   j                  «       S rF   )rG   Ú__str__rV   s    r   rX   zPotentialCallWrapper.__str__Ø   s   € Ø�}‰}×$Ñ$Ó&Ð&r   N)rI   ÚobjectÚreturnÚNone)rM   r0   rZ   rY   )rS   r0   rZ   r0   )rZ   r0   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__rJ   rN   rP   rR   rU   rX   © r   r   r<   r<   À   s%   „ ñó
 ó=ó+ó5ó(ô'r   c                  ó0   — e Zd ZdZdd„Zdd„Zd	d„Zd
d„Zy)ÚCallMappingz¸
    Read-only mapping that turns a C{()}-suffix in key names into an invocation
    of the key rather than a lookup of the key.

    Implementation support for L{formatWithCall}.
    c                ó   — || _         y)zo
        @param submapping: Another read-only mapping which will be used to look
            up items.
        N)Ú_submapping)rH   Ú
submappings     r   rJ   zCallMapping.__init__ä   s   € ð
 &ˆÕr   c                ó,   — t        | j                  «      S rF   )Úiterrd   rV   s    r   Ú__iter__zCallMapping.__iter__ë   s   € Ü�D×$Ñ$Ó%Ð%r   c                ó,   — t        | j                  «      S rF   )Úlenrd   rV   s    r   Ú__len__zCallMapping.__len__î   s   € Ü�4×#Ñ#Ó$Ð$r   c                óB   — t        || j                  j                  «      S )z|
        Look up an item in the submapping for this L{CallMapping}, calling it
        if C{key} ends with C{"()"}.
        )rC   rd   rP   )rH   r"   s     r   rP   zCallMapping.__getitem__ñ   s   € ô
 �s˜D×,Ñ,×8Ñ8Ó9Ð9r   N)re   úMapping[str, Any]rZ   r[   )rZ   zIterator[Any])rZ   Úint)r"   r0   rZ   r   )r\   r]   r^   r_   rJ   rh   rk   rP   r`   r   r   rb   rb   Ü   s   „ ñó&ó&ó%ô:r   rb   c           	     óT   — t        t        j                  | dt        |«      «      «      S )añ  
    Format a string like L{str.format}, but:

        - taking only a name mapping; no positional arguments

        - with the additional syntax that an empty set of parentheses
          correspond to a formatting item that should be called, and its result
          C{str}'d, rather than calling C{str} on the element directly as
          normal.

    For example::

        >>> 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`   )r0   r   Úvformatrb   )ÚformatStringÚmappings     r   ÚformatWithCallrs   ù   s#   € ô. Œz×!Ñ! ,°´KÀÓ4HÓIÓJÐJr   c                ón  — 	 d| v rt        | «      S t        t        t        t        t
        f      | j                  dd«      «      }|€yt        |t        «      rn0t        |t
        «      r|j                  d«      }nt        d|›�«      ‚t        || «      S # t        $ r}t        | |«      cY d}~S d}~ww xY w)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_formatNÚ zutf-8zLog format must be str, not )r   r   r	   r
   r0   ÚbytesÚgetÚ
isinstanceÚdecodeÚ	TypeErrorrs   r(   r*   )r   r'   Úes      r   Ú_formatEventr~     s«   € ð2Ø˜eÑ#Ü˜eÓ$Ð$ä”hœu¤S¬% ZÑ0Ñ1°5·9±9¸\È4Ó3PÓQˆØˆ>Øô �fœcÔ"ØÜ˜¤Ô&Ø—]‘] 7Ó+‰FäÐ:¸6¸*ÐEÓFÐFä˜f eÓ,Ð,øäò 2Ü'¨¨qÓ1Õ1ûð2ús)   ‚B ‘6B ÁAB Â	B4ÂB/Â)B4Â/B4c                ór   — 	 | j                  «       }|S # t        $ r}dt        |«      z   }Y d}~|S d}~ww xY w)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   Ú_formatTracebackr‚   5  sF   € ðHØ×(Ñ(Ó*ˆ	ð Ðøô ò HØ>ÄÀQÃÑGŒ	ØÐûðHús   ‚ ”	6�1±6c           	     ój  — t        t        t           | j                  dd«      «      }|€kt        t        t           | j                  dd«      «      }|€d}n|j
                  }dj                  t        t        | j                  dd«      «      |¬«      }|S 	 t        |«      }|S # t        $ r d}Y |S w xY w)	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)Ú	namespaceÚlevelÚUNFORMATTABLE)r   r	   r0   ry   r   rM   r'   Ú	Exception)r   Úsystemrˆ   Ú	levelNames       r   Ú_formatSystemr�   G  s·   € ô ”(œ3‘- §¡¨<¸Ó!>Ó?€FØ€~Ü”XœmÑ,¨e¯i©i¸ÀTÓ.JÓKˆØˆ=Ø‰IàŸ
™
ˆIà&×-Ñ-Üœ3 §	¡	¨/¸3Ó ?Ó@Øð .ó 
ˆð €Mð		%Ü˜“[ˆFð €Møô ò 	%Ø$‰FØ€Mð	%ús   ÂB# Â#B2Â1B2Tc                óT  — t        | «      }|r'd| v r#| d   }t        |«      }dj                  ||f«      }|s|S d}|r7dj                   |t        t        | j                  dd«      «      «      dg«      }d}	|rdj                  dt        | «      ddg«      }	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_failurer8   rw   Úlog_timeNú ú[ú]z{timeStamp}{system}{eventText})Ú	timeStampr‹   r:   )r~   r‚   r    r   Úfloatry   r�   r'   )
r   r   r   r   r6   r:   Úfr�   r”   r‹   s
             r   r   r   f  sÁ   € ôT ˜UÓ#€IÙ˜M¨UÑ2Ø�-Ñ ˆÜ$ QÓ'ˆ	Ø—I‘I˜y¨)Ð4Ó5ˆ	áØÐà€IÙØ—G‘G™Z¬¬U°E·I±I¸jÈ$Ó4OÓ(PÓQÐSVÐWÓXˆ	à€FÙØ—‘˜#œ}¨UÓ3°S¸#Ð>Ó?ˆà+×2Ñ2ØØØð 3ó ð r   N)r   r   rZ   r0   )r   r   r   r(   rZ   r0   )r2   zOptional[float]r3   úOptional[str]r4   r0   rZ   r0   )r   r   r6   z Callable[[Optional[float]], str]rZ   r—   )r"   r0   r@   zCallable[[str], Any]rZ   r<   )rq   r0   rr   rm   rZ   r0   )r%   r   rZ   r0   )r   r   r   Úboolr   r˜   r   r˜   r6   zCallable[[float], str]rZ   r0   ))r_   Ú
__future__r   r   r.   Útypingr   r   r   r   r	   r
   r   Ú
constantlyr   Útwisted.python._tzhelperr   Útwisted.python.failurer   Útwisted.python.reflectr   Ú_flattenr   r   Ú_interfacesr   ÚtimeFormatRFC3339r   r*   r6   r;   rC   rY   r<   r0   rb   rs   r~   r‚   r�   r   r`   r   r   ú<module>r¢      s  ðñ
õ #å )ß J× JÑ Jå $å 8Ý *Ý ,ß ,Ý !à)Ð óó(!
ðL !2Øð2Ø
ð2àð2ð ð2ð 	ó	2ðF EOð3Øð3Ø!Að3àó3ól'ô.'˜6ô 'ô8:�'˜#˜s˜(Ñ#ô :ó:Kó42óDó$ðB "Ø!ØØ)3ð?Øð?àð?ð ð?ð ð	?ð
 'ð?ð 	ô?r   