
    Yf4                    B   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d8dZd9d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$d8d+Z%d>d.Z&d8d/Z'd0d0d0efd?d6Z(d7S )@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%zeventr   returnstrc                (    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)r   s    H/var/www/html/env/lib/python3.11/site-packages/twisted/logger/_format.pyformatEventr      s'     	       errorBaseExceptionc                   	 d                     | |          S # t          $ rg t                      }d                    d |                                 D                       }d                     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   r   z, c              3  ~   K   | ]8\  }}d                      t          |          t          |          f          V  9dS )z = N)joinr   ).0keyvalues      r   	<genexpr>z+formatUnformattableEvent.<locals>.<genexpr>C   sY       
 
U JJ	#	%(8(89::
 
 
 
 
 
r   zrMESSAGE LOST: unformattable object logged: {error}
Recoverable data: {text}
Exception during formatting:
{failure})r   failuretext)formatr    r   r#   itemsr   )r   r   r(   r)   s       r   formatUnformattableEventr,   -   s    
:AAu B 
 
 	
  
 
 
 ))yy 
 
#kkmm
 
 
 
 
66<f&&d 7= 7 7	
 	
 	

s    A.B
	B
-whenOptional[float]
timeFormatOptional[str]defaultc                    || |S t          j        |           }t          j        | |          }t	          |                    |                    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fromtimestampr   strftime)r.   r0   r2   tzr   s        r   
formatTimer9   Q   sQ    4 T\ 3D99)$338$$Z00111r   r9    Callable[[Optional[float]], str]c                b    t          | |          }|sdS |                    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.
    )r9   N
z
	)r   replace)r   r9   	eventTexts      r   formatEventAsClassicLogTextr?   s   sD    ^ Ej999I t!!$//Itr   r%   getterCallable[[str], Any]PotentialCallWrapperc                    |                      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)endswithrB   )r%   r@   callitrealKeyr&   s        r   keycallrH      sY     \\$F )c#2#hhcGF7OOE &&&r   c                  B    e Zd ZdZddZdd	Zdd
ZddZddZddZ	dS )rB   z
    Object wrapper that wraps C{getattr()} so as to process call-parentheses
    C{"()"} after a dotted attribute access.
    wrappedobjectr   Nonec                    || _         d S N)_wrapped)selfrJ   s     r   __init__zPotentialCallWrapper.__init__   s    r   namer   c                6    t          || j        j                  S rN   )rH   rO   __getattribute__)rP   rR   s     r   __getattr__z PotentialCallWrapper.__getattr__   s    tT];<<<r   c                :    | j         |         }t          |          S rN   )rO   rB   )rP   rR   r&   s      r   __getitem__z PotentialCallWrapper.__getitem__   s     d##E***r   format_specc                6    | j                             |          S rN   )rO   
__format__)rP   rX   s     r   rZ   zPotentialCallWrapper.__format__   s    }''444r   c                4    | j                                         S rN   )rO   __repr__rP   s    r   r\   zPotentialCallWrapper.__repr__   s    }%%'''r   c                4    | j                                         S rN   )rO   __str__r]   s    r   r_   zPotentialCallWrapper.__str__   s    }$$&&&r   N)rJ   rK   r   rL   )rR   r   r   rK   )rX   r   r   r   )r   r   )
__name__
__module____qualname____doc__rQ   rU   rW   rZ   r\   r_    r   r   rB   rB      s         
       = = = =+ + + +5 5 5 5( ( ( (' ' ' ' ' 'r   c                  2    e Zd ZdZddZddZdd
ZddZdS )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}.
    
submappingMapping[str, Any]r   rL   c                    || _         dS )zo
        @param submapping: Another read-only mapping which will be used to look
            up items.
        N)_submapping)rP   rg   s     r   rQ   zCallMapping.__init__   s    
 &r   Iterator[Any]c                *    t          | j                  S rN   )iterrj   r]   s    r   __iter__zCallMapping.__iter__   s    D$%%%r   intc                *    t          | j                  S rN   )lenrj   r]   s    r   __len__zCallMapping.__len__   s    4#$$$r   r%   r   r   c                6    t          || j        j                  S )z|
        Look up an item in the submapping for this L{CallMapping}, calling it
        if C{key} ends with C{"()"}.
        )rH   rj   rW   )rP   r%   s     r   rW   zCallMapping.__getitem__   s    
 sD,8999r   N)rg   rh   r   rL   )r   rk   )r   ro   )r%   r   r   r   )r`   ra   rb   rc   rQ   rn   rr   rW   rd   r   r   rf   rf      sn         & & & && & & &% % % %: : : : : :r   rf   formatStringmappingrh   c           	     b    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.
    rd   )r   r   vformatrf   )rt   ru   s     r   formatWithCallrx      s)    . z!,K4H4HIIJJJr   c                   	 d| v rt          |           S t          t          t          t          t
          f                  |                     dd                    }|dS t          |t                    rn=t          |t
                    r|                    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
   r   bytesget
isinstancedecode	TypeErrorrx   r    r,   )r   r*   es      r   _formatEventr     s    2e##e$$$huS%Z01599\43P3PQQ>2 fc"" 	G&& 	G]]7++FFE6EEFFFfe,,, 2 2 2'q111111112s*   C AC A"C 
C&C!C&!C&r(   r   c                    	 |                                  }n)# t          $ r}dt          |          z   }Y d}~nd}~ww xY w|S )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    r   )r(   	tracebackr   s      r   _formatTracebackr   5  s^    H((**		 H H H>QG						Hs    
=8=c           	        t          t          t                   |                     dd                    }|t          t          t                   |                     dd                    }|d}n|j        }d                    t          t          |                     dd                    |          }n#	 t          |          }n# t          $ r d}Y nw xY w|S )	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	   r   r~   r   rR   r*   	Exception)r   systemr   	levelNames       r   _formatSystemr   G  s     (3-<!>!>??F~Xm,eiiT.J.JKK=II
I&--3		/3 ? ?@@ . 
 

	%[[FF 	% 	% 	%$FFF	%Ms   7C CCTr   boolr   r   Callable[[float], str]c                   t          |           }|r2d| v r.| d         }t          |          }d                    ||f          }|s|S d}|rGd                     |t          t          |                     dd                              dg          }d}	|r&d                    dt          |           ddg          }	d	                    ||	|
          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_failurer<   r|   log_timeN []z{timeStamp}{system}{eventText})	timeStampr   r>   )r   r   r#   r   floatr~   r   r*   )
r   r   r   r   r9   r>   fr   r   r   s
             r   r   r   f  s    T U##I 6MU22- $Q''	IIy)455	 I YGGZZUEIIj$4O4O(P(PQQSVWXX	F @#}U33S#>??+22 3   r   N)r   r   r   r   )r   r   r   r    r   r   )r.   r/   r0   r1   r2   r   r   r   )r   r   r9   r:   r   r1   )r%   r   r@   rA   r   rB   )rt   r   ru   rh   r   r   )r(   r   r   r   )r   r   r   r   r   r   r   r   r9   r   r   r   ))rc   
__future__r   r   r5   typingr   r   r   r   r	   r
   r   
constantlyr   twisted.python._tzhelperr   twisted.python.failurer   twisted.python.reflectr   _flattenr   r   _interfacesr   timeFormatRFC3339r   r,   r9   r?   rH   rK   rB   r   rf   rx   r   r   r   r   rd   r   r   <module>r      sG  
  # " " " " " ) ) ) ) ) ) J J J J J J J J J J J J J J J J J J $ $ $ $ $ $ 8 8 8 8 8 8 * * * * * * , , , , , , , , , , , , , , ! ! ! ! ! !)    (!
 !
 !
 !
L !22 2 2 2 2F EO3 3 3 3 3l' ' ' '.' ' ' ' '6 ' ' '8: : : : :'#s(# : : ::K K K K42 2 2 2D   $   B "!)3? ? ? ? ? ? ?r   