
    Vh?                        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e      Z G d d      Z G d d      Z G d d      Z e       ZddZy)z
Logger class.
    )annotations)time)TracebackType)AnyCallableContextManagerOptionalProtocolcast)currentframe)Failure   )ILogObserverLogTrace)InvalidLogLevelErrorLogLevelc                  F    e Zd ZdZedd       Zedd       Zedd       Zy)	Operationz
    An L{Operation} represents the success (or lack thereof) of code performed
    within the body of the L{Logger.failureHandler} context manager.
    c                     y)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 selfs    F/home/dcms/DCMS/lib/python3.12/site-packages/twisted/logger/_logger.py	succeededzOperation.succeeded           c                     y)zj
        Did the operation raise an exception?  If so, this L{Failure} is that
        exception.
        Nr   r   s    r   failurezOperation.failure#   r   r   c                     y)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   s    r   failedzOperation.failed*   r   r   Nreturnbool)r"   Failure | None)__name__
__module____qualname____doc__propertyr   r   r    r   r   r   r   r      sC    
      r   r   c                  d    e Zd ZU dZded<   dZded<   ddZedd       Zdd	Z		 	 	 	 	 	 	 	 dd
Z
y)_FailCtxMgrFr#   r   Nr$   r   c                    || _         y N_failr   fails     r   __init__z_FailCtxMgr.__init__7   	    
r   c                    | j                   d uS r-   r   r   s    r   r    z_FailCtxMgr.failed:   s    ||4''r   c                    | S r-   r   r   s    r   	__enter__z_FailCtxMgr.__enter__>   s    r   c               \    |#t               }|| _        | j                  |       yd| _        yNT)r   r   r/   r   r   exc_type	exc_value	tracebackr   s        r   __exit__z_FailCtxMgr.__exit__A   s5     iG"DLJJw  "DNr   r1   zCallable[[Failure], None]r"   Noner!   )r"   r   r;   ztype[BaseException] | Noner<   zBaseException | Noner=   zTracebackType | Noner"   r#   )r%   r&   r'   r   __annotations__r   r2   r)   r    r7   r>   r   r   r   r+   r+   3   s_    It"G^" ( (, ( (	 
r   r+   c                  4    e Zd ZddZddZ	 	 	 	 	 	 	 	 ddZy)_FastFailCtxMgrc                    || _         y r-   r.   r0   s     r   r2   z_FastFailCtxMgr.__init__R   r3   r   c                     y r-   r   r   s    r   r7   z_FastFailCtxMgr.__enter__U   s    r   c               L    |"t               }|| _        | j                  |       yr9   )r   r   r/   r:   s        r   r>   z_FastFailCtxMgr.__exit__X   s'     iG"DLJJwr   Nr?   )r"   r@   rA   )r%   r&   r'   r2   r7   r>   r   r   r   rD   rD   Q   s7    , ( (	 
r   rD   c                  *   e Zd ZdZedd       Z	 	 	 d	 	 	 	 	 	 	 ddZdddZddZ	 d	 	 	 	 	 	 	 ddZ	de
j                  f	 	 	 	 	 	 	 	 	 ddZddd	Zddd
ZdddZdddZdddZe
j                  f	 	 	 	 	 	 	 ddZe
j                  f	 	 	 	 	 ddZy)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.
    c                 n    	 t        t        t        d      j                  d         S # t        $ r Y yw xY 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>)r   strr   	f_globalsKeyErrorr   r   r   _namespaceFromCallingContextz#Logger._namespaceFromCallingContextq   s5    	\!_66zBCC 		s   %( 	44Nc                r    || j                         }|| _        || _        |ddlm} || _        y|| _        y)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)rO   	namespacesource_globalrQ   observer)r   rR   rS   rU   rQ   s        r   r2   zLogger.__init__}   s=      99;I"3*<DM$DMr   c                    |J ||}n|}| j                  dj                  |j                  |j                  g      || j                        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}.
        .)rU   )	__class__joinr&   r%   rU   )r   instanceownerrS   s       r   __get__zLogger.__get__   s[    &    FF~~HHe&&78]]  
 	
r   c                P    d| j                   j                   d| j                  dS )N< >)rX   r%   rR   r   s    r   __repr__zLogger.__repr__   s'    4>>**+1T^^,>a@@r   c           	     p   |t        j                         vr(| j                  dt        t	        |            ||        y|}|j                  | || j                  | j                  |t                      d|v r.t        t        |d         j                  | | j                  f       | j                  |       y)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().)invalidLevelloggerN)
log_logger	log_levellog_namespace
log_source
log_formatlog_time	log_trace)r   iterconstantsr   r   r   updaterR   rS   r   r   r   appendrU   )r   levelformatkwargsevents        r   emitzLogger.emit   s     ..00LLL,U34"	   ..{{V 	 	
 %5-.55tT]]6KLer   c                H    |
t               } | j                  ||fd|i| y)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}
        Nlog_failure)r   rs   )r   rp   r   ro   rq   s        r   r   zLogger.failure   s+    d ?iG		%?W??r   c                H     | j                   t        j                  |fi | y)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)rs   r   debugr   rp   rq   s      r   rw   zLogger.debug       			(..&3F3r   c                H     | j                   t        j                  |fi | y)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)rs   r   inforx   s      r   r{   zLogger.info*       			(--262r   c                H     | j                   t        j                  |fi | y)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)rs   r   warnrx   s      r   r~   zLogger.warn9  r|   r   c                H     | j                   t        j                  |fi | y)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)rs   r   errorrx   s      r   r   zLogger.errorH  ry   r   c                H     | j                   t        j                  |fi | y)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)rs   r   criticalrx   s      r   r   zLogger.criticalW  s     			(##V6v6r   c                ,     t         f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                .     j                   | fi S r-   r5   )frp   rq   ro   r   s    r   <lambda>z(Logger.failuresHandled.<locals>.<lambda>  s    \T\\&!U%Mf%M r   )r+   )r   rp   ro   rq   s   ````r   failuresHandledzLogger.failuresHandledf  s    T MNNr   c                (     t         f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                *    j                  |       S r-   r5   )r   ro   r   staticMessages    r   r   z'Logger.failureHandler.<locals>.<lambda>  s    mQ)N r   )rD   )r   r   ro   s   ```r   failureHandlerzLogger.failureHandler  s    V NOOr   )r"   rL   )NNN)rR   Optional[str]rS   zOptional[object]rU   zOptional['ILogObserver']r"   r@   r-   )rZ   objectr[   zOptional[type]r"   z'Logger')ro   r   rp   r   rq   r   r"   r@   )
rp   rL   r   zOptional[Failure]ro   r   rq   r   r"   r@   )rp   r   rq   r   r"   r@   )rp   rL   ro   r   rq   r   r"   zContextManager[Operation])r   rL   ro   r   r"   zContextManager[None])r%   r&   r'   r(   staticmethodrO   r2   r\   ra   rs   r   r   r   rw   r{   r~   r   r   r   r   r   r   rI   rI   f   sQ    	 	 $(#'-1	% % !% +	%
 
%:
@A 8<%%'4%GM%	%T &*"++	5@5@ #5@ 	5@
 5@ 
5@n43347  .6->->*O*O"**OJP*O	"*O^ #+++P+P +P 
	+Pr   rI   c                B    t         j                  | | j                        S )z?
    Get a L{Logger} instance attached to the given class.
    )_logr\   rX   )objs    r   
_loggerForr     s     <<S]]++r   N)r   r   r"   rI   )r(   
__future__r   r   typesr   typingr   r   r   r	   r
   r   twisted.python.compatr   twisted.python.failurer   _interfacesr   r   _levelsr   r   r   r+   rD   rI   r   r   r   r   r   <module>r      sd   
 #   J J . * / 3 < < *WP WPt
 x,r   