
    Yf?                       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dS )z
Logger class.
    )annotations)time)TracebackType)AnyCallableContextManagerOptionalProtocolcast)currentframe)Failure   )ILogObserverLogTrace)InvalidLogLevelErrorLogLevelc                  Z    e Zd ZdZed	d            Zed
d            Ze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                    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 selfs    H/var/www/html/env/lib/python3.11/site-packages/twisted/logger/_logger.py	succeededzOperation.succeeded             Failure | Nonec                    dS )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                    dS )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r   r   )r   r   )__name__
__module____qualname____doc__propertyr   r!   r#   r   r   r   r   r      s~         
    X    X    X  r   r   c                  \    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
dS )_FailCtxMgrFr   r   Nr   r!   failCallable[[Failure], None]r   Nonec                    || _         d S N_failr   r,   s     r   __init__z_FailCtxMgr.__init__7       


r   c                    | j         d uS r0   r!   r   s    r   r#   z_FailCtxMgr.failed:   s    |4''r   r   c                    | S r0   r   r   s    r   	__enter__z_FailCtxMgr.__enter__>   s    r   exc_typetype[BaseException] | None	exc_valueBaseException | None	tracebackTracebackType | Nonec               n    |+t                      }|| _        |                     |           nd| _        dS NT)r   r!   r2   r   r   r:   r<   r>   r!   s        r   __exit__z_FailCtxMgr.__exit__A   s;     iiG"DLJJw!DNtr   r,   r-   r   r.   r$   )r   r   r:   r;   r<   r=   r>   r?   r   r   )r%   r&   r'   r   __annotations__r!   r4   r)   r#   r9   rC   r   r   r   r+   r+   3   s         I"G""""    ( ( ( X(        r   r+   c                  &    e Zd ZddZddZddZdS )_FastFailCtxMgrr,   r-   r   r.   c                    || _         d S r0   r1   r3   s     r   r4   z_FastFailCtxMgr.__init__R   r5   r   c                    d S r0   r   r   s    r   r9   z_FastFailCtxMgr.__enter__U   s    r   r:   r;   r<   r=   r>   r?   r   c               ^    |*t                      }|| _        |                     |           dS rA   )r   r!   r2   rB   s        r   rC   z_FastFailCtxMgr.__exit__X   s1     iiG"DLJJwtr   NrD   )r   r.   rE   )r%   r&   r'   r4   r9   rC   r   r   r   rH   rH   Q   sP                   r   rH   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d0d&ZdS )1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                     	 t          t          t          d          j        d                   S # t          $ r Y dS 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   rN   r   	f_globalsKeyErrorr   r   r   _namespaceFromCallingContextz#Logger._namespaceFromCallingContextq   sG    	\!__6zBCCC 	 	 	;;	s   ,/ 
==N	namespaceOptional[str]sourceOptional[object]observerOptional['ILogObserver']r.   c                ~    ||                                  }|| _        || _        |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)rS   rT   rV   _globalr[   rX   )r   rT   rV   rX   r[   s        r   r4   zLogger.__init__}   sW      99;;I"333333*<DMMM$DMMMr   instanceobjectownerOptional[type]'Logger'c                    |J ||}n|}|                      d                    |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}.
        N.)rX   )	__class__joinr&   r%   rX   )r   r]   r_   rV   s       r   __get__zLogger.__get__   s^    &    FFF~~HHe&788]  
 
 	
r   c                2    d| j         j         d| j        dS )N< >)rd   r%   rT   r   s    r   __repr__zLogger.__repr__   s"    @4>*@@T^@@@@r   levelr   formatkwargsc           	        |t          j                    vr5|                     dt          t	          |                    ||            dS |}|                    | || j        | j        |t                                 d|v r5t          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().)invalidLevelloggerN)
log_logger	log_levellog_namespace
log_source
log_formatlog_time	log_trace)r   iterconstantsr!   r   r   updaterT   rV   r   r   r   appendrX   )r   rl   rm   rn   events        r   emitzLogger.emit   s     .0000LLL,U3344"	     F.{VV 	 	
 	
 	
 %5-..55tT]6KLLLer   r!   Optional[Failure]c                H    |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}
        Nlog_failure)r   r}   )r   rm   r!   rl   rn   s        r   r!   zLogger.failure   s:    d ?iiG	%??W??????r   c                8     | 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)r}   r   debugr   rm   rn   s      r   r   zLogger.debug  (     		(.&33F33333r   c                8     | j         t          j        |fi | dS )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)r}   r   infor   s      r   r   zLogger.info*  (     		(-22622222r   c                8     | j         t          j        |fi | dS )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)r}   r   warnr   s      r   r   zLogger.warn9  r   r   c                8     | j         t          j        |fi | dS )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)r}   r   errorr   s      r   r   zLogger.errorH  r   r   c                8     | j         t          j        |fi | dS )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)r}   r   criticalr   s      r   r   zLogger.criticalW  s)     		(#V66v66666r   ContextManager[Operation]c                4     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 r0   r7   )frm   rn   rl   r   s    r   <lambda>z(Logger.failuresHandled.<locals>.<lambda>  s    \T\&!U%M%Mf%M%M r   )r+   )r   rm   rl   rn   s   ````r   failuresHandledzLogger.failuresHandledf  s*    T MMMMMMMNNNr   staticMessageContextManager[None]c                0     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                2                         |           S r0   r7   )r   rl   r   r   s    r   r   z'Logger.failureHandler.<locals>.<lambda>  s    mQ)N)N r   )rH   )r   r   rl   s   ```r   failureHandlerzLogger.failureHandler  s&    V NNNNNNOOOr   )r   rN   )NNN)rT   rU   rV   rW   rX   rY   r   r.   r0   )r]   r^   r_   r`   r   ra   )rl   r   rm   rU   rn   r^   r   r.   )
rm   rN   r!   r~   rl   r   rn   r^   r   r.   )rm   rU   rn   r^   r   r.   )rm   rN   rl   r   rn   r^   r   r   )r   rN   rl   r   r   r   )r%   r&   r'   r(   staticmethodrS   r4   rf   rk   r}   r   r   r!   r   r   r   r   r   r   r   r   r   rM   rM   f   s         	 	 	 \	 $(#'-1	% % % % %:
 
 
 
 
@A A A A 8<% % % % %T &*"+	5@ 5@ 5@ 5@ 5@n4 4 4 4 43 3 3 3 33 3 3 3 34 4 4 4 47 7 7 7 7  .6->*O *O *O *O *O^ #++P +P +P +P +P +P +Pr   rM   objr^   r   c                B    t                               | | j                  S )z?
    Get a L{Logger} instance attached to the given class.
    )_logrf   rd   )r   s    r   
_loggerForr     s     <<S]+++r   N)r   r^   r   rM   )r(   
__future__r   r   typesr   typingr   r   r   r	   r
   r   twisted.python.compatr   twisted.python.failurer   _interfacesr   r   _levelsr   r   r   r+   rH   rM   r   r   r   r   r   <module>r      s  
  # " " " " "             J J J J J J J J J J J J J J J J . . . . . . * * * * * * / / / / / / / / 3 3 3 3 3 3 3 3       <       <       *WP WP WP WP WP WP WP WPt
 vxx, , , , , ,r   