o
    h'                     @  sB  d Z ddlmZ ddlZddlZddlmZmZmZ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	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 G dd deZG dd dZe efZ!d%ddZ"G dd dZ#G dd deZeeG dd dZ$eeG dd  d Z%d&d!d"Z&G d#d$ d$Z'dS )'z
Processors and tools specific to the `Twisted <https://twisted.org/>`_
networking engine.

See also :doc:`structlog's Twisted support <twisted>`.
    )annotationsN)AnyCallableSequenceTextIOlog)Failure)ILogObservertextFromEventDict)implementer   )BoundLoggerBase)_BUILTIN_DEFAULT_PROCESSORS)until_not_interrupted)JSONRenderer)	EventDictWrappedLoggerc                   @  s(   e Zd ZdZdddd	Zddd
dZdS )BoundLoggera  
    Twisted-specific version of `structlog.BoundLogger`.

    Works exactly like the generic one except that it takes advantage of
    knowing the logging methods in advance.

    Use it like::

        configure(
            wrapper_class=structlog.twisted.BoundLogger,
        )

    Nevent
str | Nonekwr   returnc                 K     | j d|fi |S )zG
        Process event and call ``log.msg()`` with the result.
        msg_proxy_to_loggerselfr   r    r   G/var/www/html/ai/venv/lib/python3.10/site-packages/structlog/twisted.pyr   /      zBoundLogger.msgc                 K  r   )zG
        Process event and call ``log.err()`` with the result.
        errr   r   r   r   r    r"   5   r!   zBoundLogger.errN)r   r   r   r   r   r   )__name__
__module____qualname____doc__r   r"   r   r   r   r    r       s    r   c                   @  s   e Zd ZdZd	ddZdS )
LoggerFactoryz
    Build a Twisted logger when an *instance* is called.

    >>> from structlog import configure
    >>> from structlog.twisted import LoggerFactory
    >>> configure(logger_factory=LoggerFactory())
    argsr   r   r   c                 G  s   t S )z
        Positional arguments are silently ignored.

        :rvalue: A new Twisted logger.

        .. versionchanged:: 0.4.0
            Added support for optional positional arguments.
        r   )r   r)   r   r   r    __call__E   s   	zLoggerFactory.__call__N)r)   r   r   r   r$   r%   r&   r'   r*   r   r   r   r    r(   <   s    r(   	eventDictr   r   tuple[Any, Any, EventDict]c                 C  s   |  dd}|  dd}|  dd}t|tr t|tr td|r+t|tr+tdt|ts;t|tr;|p8d}|}t|trB|}|sMt dkrMt }t|tr[t|ts[t|}||| fS )	z
    Removes all possible *_why*s and *_stuff*s, analyzes exc_info and returns
    a tuple of ``(_stuff, _why, eventDict)``.

    **Modifies** *eventDict*!
    _stuffN_whyr   z3Both _stuff and event contain an Exception/Failure.z!Both `_why` and `event` supplied.error)NNN)	pop
isinstance_FAIL_TYPES
ValueErrorstrsysexc_infor	   BaseException)r,   r.   r/   r   r   r   r    _extractStuffAndWhyT   s"   

r9   c                   @  s.   e Zd ZdZdddZdddZdddZdS )ReprWrappera  
    Wrap a string and return it as the ``__repr__``.

    This is needed for ``twisted.python.log.err`` that calls `repr` on
    ``_stuff``:

    >>> repr("foo")
    "'foo'"
    >>> repr(ReprWrapper("foo"))
    'foo'

    Note the extra quotes in the unwrapped example.
    stringr5   r   Nonec                 C  
   || _ d S r#   r;   )r   r;   r   r   r    __init__      
zReprWrapper.__init__otherobjectboolc                 C  s   t || jo| j|jkS )z5
        Check for equality, just for tests.
        )r2   	__class__r;   )r   rA   r   r   r    __eq__   s   zReprWrapper.__eq__c                 C  s   | j S r#   r>   )r   r   r   r    __repr__   s   zReprWrapper.__repr__N)r;   r5   r   r<   )rA   rB   r   rC   )r   r5   )r$   r%   r&   r'   r?   rE   rF   r   r   r   r    r:   y   s
    

r:   c                   @  s   e Zd ZdZdd
dZdS )r   a  
    Behaves like `structlog.processors.JSONRenderer` except that it formats
    tracebacks and failures itself if called with ``err()``.

    .. note::

        This ultimately means that the messages get logged out using ``msg()``,
        and *not* ``err()`` which renders failures in separate lines.

        Therefore it will break your tests that contain assertions using
        `flushLoggedErrors
        <https://docs.twisted.org/en/stable/api/
        twisted.trial.unittest.SynchronousTestCase.html#flushLoggedErrors>`_.

    *Not* an adapter like `EventAdapter` but a real formatter.  Also does *not*
    require to be adapted using it.

    Use together with a `JSONLogObserverWrapper`-wrapped Twisted logger like
    `plainJSONStdOutLogger` for pure-JSON logs.
    loggerr   namer5   r,   r   r   $tuple[Sequence[Any], dict[str, Any]]c                 C  sh   t |\}}}|dkr!||d< t|tr |jdd|d< |  n||d< tt| |||fddifS )Nr"   r   verbose)detail	exception
_structlogT)r9   r2   r	   getTracebackcleanFailurer:   GenericJSONRendererr*   r   rG   rH   r,   r.   r/   r   r   r    r*      s    
zJSONRenderer.__call__N)rG   r   rH   r5   r,   r   r   rI   r+   r   r   r   r    r      s    r   c                   @  s$   e Zd ZdZdddZdd
dZdS )PlainFileLogObserverz
    Write only the plain message without timestamps or anything else.

    Great to just print JSON to stdout where you catch it with something like
    runit.

    Arguments:

        file: File to print to.

    .. versionadded:: 0.2.0
    filer   r   r<   c                 C  s   |j | _|j| _d S r#   )write_writeflush_flush)r   rS   r   r   r    r?      s   zPlainFileLogObserver.__init__r,   r   c                 C  s"   t | jt|d  t | j d S )N
)r   rU   r   rW   r   r,   r   r   r    r*      s   zPlainFileLogObserver.__call__N)rS   r   r   r<   )r,   r   r   r<   r$   r%   r&   r'   r?   r*   r   r   r   r    rR      s    
rR   c                   @  s$   e Zd ZdZdddZdddZdS )JSONLogObserverWrappera  
    Wrap a log *observer* and render non-`JSONRenderer` entries to JSON.

    Arguments:

        observer (ILogObserver):
            Twisted log observer to wrap.  For example
            :class:`PlainFileObserver` or Twisted's stock `FileLogObserver
            <https://docs.twisted.org/en/stable/api/
            twisted.python.log.FileLogObserver.html>`_

    .. versionadded:: 0.2.0
    observerr   r   r<   c                 C  r=   r#   )	_observer)r   r\   r   r   r    r?      r@   zJSONLogObserverWrapper.__init__r,   r   r5   c                 C  s:   d|vrt t||ddf|d< d|d< | |S )NrM   system)r   r^   messageT)jsondumpsr   getr]   rY   r   r   r    r*      s   

zJSONLogObserverWrapper.__call__N)r\   r   r   r<   )r,   r   r   r5   rZ   r   r   r   r    r[      s    
r[   c                   C  s   t ttjS )a  
    Return a logger that writes only the message to stdout.

    Transforms non-`JSONRenderer` messages to JSON.

    Ideal for JSONifying log entries from Twisted plugins and libraries that
    are outside of your control::

        $ twistd -n --logger structlog.twisted.plainJSONStdOutLogger web
        {"event": "Log opened.", "system": "-"}
        {"event": "twistd 13.1.0 (python 2.7.3) starting up.", "system": "-"}
        {"event": "reactor class: twisted...EPollReactor.", "system": "-"}
        {"event": "Site starting on 8080", "system": "-"}
        {"event": "Starting factory <twisted.web.server.Site ...>", ...}
        ...

    Composes `PlainFileLogObserver` and `JSONLogObserverWrapper` to a usable
    logger.

    .. versionadded:: 0.2.0
    )r[   rR   r6   stdoutr   r   r   r    plainJSONStdOutLogger  s   rd   c                   @  s(   e Zd ZdZ	ddddZdddZdS )EventAdapterax  
    Adapt an ``event_dict`` to Twisted logging system.

    Particularly, make a wrapped `twisted.python.log.err
    <https://docs.twisted.org/en/stable/api/twisted.python.log.html#err>`_
    behave as expected.

    Arguments:

        dictRenderer:
            Renderer that is used for the actual log message. Please note that
            structlog comes with a dedicated `JSONRenderer`.

    **Must** be the last processor in the chain and requires a *dictRenderer*
    for the actual formatting as an constructor argument in order to be able to
    fully support the original behaviors of ``log.msg()`` and ``log.err()``.
    NdictRenderer5Callable[[WrappedLogger, str, EventDict], str] | Noner   r<   c                 C  s   |pt d | _d S )N)r   _dictRenderer)r   rf   r   r   r    r?   3  s   zEventAdapter.__init__rG   r   rH   r5   r,   r   r   c                 C  sD   |dkrt |\}}}||d< d|| |||dfS | |||S )Nr"   r   r   )r.   r/   )r9   ri   rQ   r   r   r    r*   :  s   zEventAdapter.__call__r#   )rf   rg   r   r<   )rG   r   rH   r5   r,   r   r   r   rZ   r   r   r   r    re      s
    re   )r,   r   r   r-   )r   r[   )(r'   
__future__r   r`   r6   typingr   r   r   r   twisted.pythonr   twisted.python.failurer	   twisted.python.logr
   r   zope.interfacer   _baser   _configr   _utilsr   
processorsr   rP   r   r   r   r(   r8   r3   r9   r:   rR   r[   rd   re   r   r   r   r    <module>   s4   
%0
#