o
    Òó·iØ?  ã                   @  sÎ   d Z ddlm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 ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ G dd„ deƒZG dd„ dƒZG dd„ dƒZG dd„ dƒZeƒ Zddd„ZdS )z
Logger class.
é    )Úannotations)Útime)ÚTracebackType)ÚAnyÚCallableÚContextManagerÚOptionalÚProtocolÚcast)Úcurrentframe)ÚFailureé   )ÚILogObserverÚLogTrace)ÚInvalidLogLevelErrorÚLogLevelc                   @  s:   e Zd ZdZeddd„ƒZeddd„ƒZedd	d
„ƒZdS )Ú	Operationz™
    An L{Operation} represents the success (or lack thereof) of code performed
    within the body of the L{Logger.failureHandler} context manager.
    ÚreturnÚboolc                 C  ó   dS )zÅ
        Did the operation succeed?  C{True} iff the code completed without
        raising an exception; C{False} while the code is running and C{False}
        if it raises an exception.
        N© ©Úselfr   r   ú\C:\Users\psant\Downloads\PAF backend\school\venv\Lib\site-packages\twisted/logger/_logger.pyÚ	succeeded   ó    zOperation.succeededúFailure | Nonec                 C  r   )zj
        Did the operation raise an exception?  If so, this L{Failure} is that
        exception.
        Nr   r   r   r   r   Úfailure#   r   zOperation.failurec                 C  r   )z³
        Did the operation fail?  C{True} iff the code raised an exception;
        C{False} while the code is running and C{False} if it completed without
        error.
        Nr   r   r   r   r   Úfailed*   r   zOperation.failedN©r   r   )r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úpropertyr   r   r   r   r   r   r   r      s    r   c                   @  sR   e Zd ZU dZded< dZded< ddd„Zeddd„ƒZddd„Z	ddd„Z
dS )Ú_FailCtxMgrFr   r   Nr   r   ÚfailúCallable[[Failure], None]r   ÚNonec                 C  ó
   || _ d S ©N©Ú_fail©r   r&   r   r   r   Ú__init__7   ó   
z_FailCtxMgr.__init__c                 C  s
   | j d uS r*   ©r   r   r   r   r   r   :   s   
z_FailCtxMgr.failedr   c                 C  s   | S r*   r   r   r   r   r   Ú	__enter__>   ó   z_FailCtxMgr.__enter__Úexc_typeútype[BaseException] | NoneÚ	exc_valueúBaseException | NoneÚ	tracebackúTracebackType | Nonec                C  s,   |d urt ƒ }|| _|  |¡ dS d| _dS ©NT)r   r   r,   r   ©r   r3   r5   r7   r   r   r   r   Ú__exit__A   s   
ÿz_FailCtxMgr.__exit__©r&   r'   r   r(   r   )r   r   ©r3   r4   r5   r6   r7   r8   r   r   )r    r!   r"   r   Ú__annotations__r   r.   r$   r   r1   r;   r   r   r   r   r%   3   s   
 

r%   c                   @  s*   e Zd Zddd„Zddd„Zddd„ZdS )Ú_FastFailCtxMgrr&   r'   r   r(   c                 C  r)   r*   r+   r-   r   r   r   r.   R   r/   z_FastFailCtxMgr.__init__c                 C  s   d S r*   r   r   r   r   r   r1   U   r2   z_FastFailCtxMgr.__enter__r3   r4   r5   r6   r7   r8   r   c                C  s"   |d urt ƒ }|| _|  |¡ dS r9   )r   r   r,   r:   r   r   r   r;   X   s
   
z_FastFailCtxMgr.__exit__Nr<   )r   r(   r=   )r    r!   r"   r.   r1   r;   r   r   r   r   r?   Q   s    

r?   c                   @  sÂ   e Zd ZdZed4dd„ƒZ			d5d6dd„Zd7d8dd„Zd4dd„Z	d7d9dd„Z	de
jfd:d!d"„Zd7d;d#d$„Zd7d;d%d&„Zd7d;d'd(„Zd7d;d)d*„Zd7d;d+d,„Ze
jfd<d.d/„Ze
jfd=d2d3„ZdS )>ÚLoggera~  
    A L{Logger} emits log messages to an observer.  You should instantiate it
    as a class or module attribute, as documented in L{this module's
    documentation <twisted.logger>}.

    @ivar namespace: the namespace for this logger
    @ivar source: The object which is emitting events via this logger
    @ivar observer: The observer that this logger will send events to.
    r   Ústrc                   C  s,   zt ttdƒjd ƒW S  ty   Y dS w )z“
        Derive a namespace from the module containing the caller's caller.

        @return: the fully qualified python name of a module.
        é   r    z	<unknown>N)r
   rA   r   Ú	f_globalsÚKeyErrorr   r   r   r   Ú_namespaceFromCallingContextq   s
   ÿz#Logger._namespaceFromCallingContextNÚ	namespaceúOptional[str]ÚsourceúOptional[object]ÚobserverúOptional['ILogObserver']r(   c                 C  sD   |du r|   ¡ }|| _|| _|du rddlm} || _dS || _dS )a3  
        @param namespace: The namespace for this logger.  Uses a dotted
            notation, as used by python modules.  If not L{None}, then the name
            of the module of the caller is used.
        @param source: The object which is emitting events via this
            logger; this is automatically set on instances of a class
            if this L{Logger} is an attribute of that class.
        @param observer: The observer that this logger will send events to.
            If L{None}, use the L{global log publisher <globalLogPublisher>}.
        Nr   )ÚglobalLogPublisher)rE   rF   rH   Z_globalrL   rJ   )r   rF   rH   rJ   rL   r   r   r   r.   }   s   

zLogger.__init__ÚinstanceÚobjectÚownerúOptional[type]ú'Logger'c                 C  s>   |dusJ ‚|du r|}n|}| j d |j|jg¡|| jd�S )a‡  
        When used as a descriptor, i.e.::

            # File: athing.py
            class Something:
                log = Logger()
                def hello(self):
                    self.log.info("Hello")

        a L{Logger}'s namespace will be set to the name of the class it is
        declared on.  In the above example, the namespace would be
        C{athing.Something}.

        Additionally, its source will be set to the actual object referring to
        the L{Logger}.  In the above example, C{Something.log.source} would be
        C{Something}, and C{Something().log.source} would be an instance of
        C{Something}.
        NÚ.)rJ   )Ú	__class__Újoinr!   r    rJ   )r   rM   rO   rH   r   r   r   Ú__get__š   s   ýzLogger.__get__c                 C  s   d| j j› d| j›d�S )Nú<ú ú>)rS   r    rF   r   r   r   r   Ú__repr__º   s   zLogger.__repr__Úlevelr   ÚformatÚkwargsc                 K  sz   |t  ¡ vr| jdtt|ƒƒ|| d� dS |}|j| || j| j|tƒ d� d|v r6t	t
|d ƒ | | jf¡ |  |¡ dS )a  
        Emit a log event to all log observers at the given level.

        @param level: a L{LogLevel}
        @param format: a message format using new-style (PEP 3101)
            formatting.  The logging event (which is a L{dict}) is
            used to render this format string.
        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        z:Got invalid log level {invalidLevel!r} in {logger}.emit().)ZinvalidLevelÚloggerN)Z
log_loggerÚ	log_levelZlog_namespaceZ
log_sourceZ
log_formatZlog_timeZ	log_trace)r   Ziterconstantsr   r   r   ÚupdaterF   rH   r   r
   r   ÚappendrJ   )r   rZ   r[   r\   Úeventr   r   r   Úemit½   s(   
üú	zLogger.emitr   úOptional[Failure]c                 K  s*   |du rt ƒ }| j||fd|i|¤Ž dS )am  
        Log a failure and emit a traceback.

        For example::

            try:
                frob(knob)
            except Exception:
                log.failure("While frobbing {knob}", knob=knob)

        or::

            d = deferredFrob(knob)
            d.addErrback(lambda f: log.failure("While frobbing {knob}",
                                               f, knob=knob))

        This method is meant to capture unexpected exceptions in code; an
        exception that is caught and handled somehow should be logged, if
        appropriate, via L{Logger.error} instead.  If some unknown exception
        occurs and your code doesn't know how to handle it, as in the above
        example, then this method provides a means to describe the failure.
        This is done at L{LogLevel.critical} by default, since no corrective
        guidance can be offered to an user/administrator, and the impact of the
        condition is unknown.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param failure: a L{Failure} to log.  If L{None}, a L{Failure} is
            created from the exception in flight.

        @param level: a L{LogLevel} to use.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.

        @see: L{Logger.failureHandler}

        @see: L{Logger.failuresHandled}
        NZlog_failure)r   rb   )r   r[   r   rZ   r\   r   r   r   r   ä   s   2zLogger.failurec                 K  ó   | j tj|fi |¤Ž dS )að  
        Emit a log event at log level L{LogLevel.debug}.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        N)rb   r   Údebug©r   r[   r\   r   r   r   re     ó   zLogger.debugc                 K  rd   )aï  
        Emit a log event at log level L{LogLevel.info}.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        N)rb   r   Úinforf   r   r   r   rh   *  rg   zLogger.infoc                 K  rd   )aï  
        Emit a log event at log level L{LogLevel.warn}.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        N)rb   r   Úwarnrf   r   r   r   ri   9  rg   zLogger.warnc                 K  rd   )að  
        Emit a log event at log level L{LogLevel.error}.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        N)rb   r   Úerrorrf   r   r   r   rj   H  rg   zLogger.errorc                 K  rd   )aó  
        Emit a log event at log level L{LogLevel.critical}.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param kwargs: additional key/value pairs to include in the event.
            Note that values which are later mutated may result in
            non-deterministic behavior from observers that schedule work for
            later execution.
        N)rb   r   Úcriticalrf   r   r   r   rk   W  rg   zLogger.criticalúContextManager[Operation]c                   s   t ‡ ‡‡‡fdd„ƒS )a/  
        Run some application code, logging a failure and emitting a traceback
        in the event that any of it fails, but continuing on.  For example::

            log = Logger(...)

            def frameworkCode() -> None:
                with log.failuresHandled("While frobbing {knob}:", knob=knob) as op:
                    frob(knob)
                if op.succeeded:
                    log.info("frobbed {knob} successfully", knob=knob)

        This method is meant to capture unexpected exceptions from application
        code; an exception that is caught and handled somehow should be logged,
        if appropriate, via L{Logger.error} instead.  If some unknown exception
        occurs and your code doesn't know how to handle it, as in the above
        example, then this method provides a means to describe the failure.
        This is done at L{LogLevel.critical} by default, since no corrective
        guidance can be offered to an user/administrator, and the impact of the
        condition is unknown.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param level: a L{LogLevel} to use.

        @param kwargs: additional key/value pairs to include in the event, if
            it is emitted.  Note that values which are later mutated may result
            in non-deterministic behavior from observers that schedule work for
            later execution.

        @see: L{Logger.failure}
        @see: L{Logger.failureHandler}

        @return: A context manager which yields an L{Operation} which will have
            either its C{succeeded} or C{failed} attribute set to C{True} upon
            completion of the code within the code within the C{with} block.
        c                   s   ˆj ˆ | ˆfi ˆ¤ŽS r*   r0   ©Úf©r[   r\   rZ   r   r   r   Ú<lambda>�  s    z(Logger.failuresHandled.<locals>.<lambda>N)r%   )r   r[   rZ   r\   r   ro   r   ÚfailuresHandledf  s   *zLogger.failuresHandledÚstaticMessageúContextManager[None]c                   s   t ‡ ‡‡fdd„ƒS )aª  
        For performance-sensitive frameworks that needs to handle potential
        failures from frequently-called application code, and do not need to
        include detailed structured information about the failure nor inspect
        the result of the operation, this method returns a context manager that
        will log exceptions and continue, that can be shared across multiple
        invocations.  It should be instantiated at module scope to avoid
        additional object creations.

        For example::

            log = Logger(...)
            ignoringFrobErrors = log.failureHandler("while frobbing:")

            def hotLoop() -> None:
                with ignoringFrobErrors:
                    frob()

        This method is meant to capture unexpected exceptions from application
        code; an exception that is caught and handled somehow should be logged,
        if appropriate, via L{Logger.error} instead.  If some unknown exception
        occurs and your code doesn't know how to handle it, as in the above
        example, then this method provides a means to describe the failure in
        nerd-speak.  This is done at L{LogLevel.critical} by default, since no
        corrective guidance can be offered to an user/administrator, and the
        impact of the condition is unknown.

        @param format: a message format using new-style (PEP 3101) formatting.
            The logging event (which is a L{dict}) is used to render this
            format string.

        @param level: a L{LogLevel} to use.

        @see: L{Logger.failure}

        @return: A context manager which does not return a value, but will
            always exit from exceptions.
        c                   s   ˆ  ˆ| ˆ ¡S r*   r0   rm   ©rZ   r   rr   r   r   rp   ½  s    z'Logger.failureHandler.<locals>.<lambda>N)r?   )r   rr   rZ   r   rt   r   ÚfailureHandler’  s   +zLogger.failureHandler)r   rA   )NNN)rF   rG   rH   rI   rJ   rK   r   r(   r*   )rM   rN   rO   rP   r   rQ   )rZ   r   r[   rG   r\   rN   r   r(   )
r[   rA   r   rc   rZ   r   r\   rN   r   r(   )r[   rG   r\   rN   r   r(   )r[   rA   rZ   r   r\   rN   r   rl   )rr   rA   rZ   r   r   rs   )r    r!   r"   r#   ÚstaticmethodrE   r.   rU   rY   rb   r   rk   r   re   rh   ri   rj   rq   ru   r   r   r   r   r@   f   s0    
ü
 ÿ*ü7ÿ/ýr@   ÚobjrN   r   c                 C  s   t  | | j¡S )z?
    Get a L{Logger} instance attached to the given class.
    N)Ú_logrU   rS   )rw   r   r   r   Ú
_loggerForÃ  s   ry   N)rw   rN   r   r@   )r#   Ú
__future__r   r   Útypesr   Útypingr   r   r   r   r	   r
   Ztwisted.python.compatr   Ztwisted.python.failurer   Z_interfacesr   r   Z_levelsr   r   r   r%   r?   r@   rx   ry   r   r   r   r   Ú<module>   s"      \