
    hW              	          S r SSKrSSKrSSKrSSKJrJr  SSKJrJr  SSK	J
r
JrJrJrJr  SSKJr  SSKJrJrJrJrJrJrJrJr  SSK J!r!  SS	K"J#r$  SS
K%J&r&J'r'J(r(J)r)  SSK*J+r+  \\,\
4   r- " S S5      r. " S S\5      r/\&R`                  " \.SS05        S r1S r2S9S jr3\3r4 " S S5      r " S S5      r\+" \5        S\5" 5       ;  ak  S r6\" \\\S9r7\6" \7Rp                  5      S 5       r8\6" \7Rr                  5      S 5       r9\6" \7Rt                  5      S 5       r:\6" \7Rv                  5      S 5       r;S \,S!\\,\
4   S"\,4S# jr<S$\-S"\\,   4S% jr= " S& S'\5      r> " S( S)\>5      r? " S* S+\>5      r@ " S, S-5      rAS. rBS:S/ jrC " S0 S15      rDS2 rES3\5" 5       ;  aR  \" \" 5       \R                  \G" \R                  S4S5      S59qI\" \" 5       \R                  \G" \R                  S4S5      S59rL " S6 S7\>5      rMS8\5" 5       ;  a  \M" 5       rNgg);z%
Logging and metrics infrastructure.
    N)ABCabstractmethod)datetimetimezone)AnyBinaryIODictOptionalcast)	Interface)LegacyLogObserverWrapperLoggerLoggingFileLogLevelLogPublisherSTDLibLogObserverglobalLogBeginnerglobalLogPublisher)LogBeginner)publishToNewObserver)contextfailurereflectutil)synchronizec                       \ rS rSrSrSrg)ILogContext%   z
Actually, this interface is just a synonym for the dictionary interface,
but it serves as a key for the default information in a log.

I do not inherit from C{Interface} because the world is a cruel place.
 N)__name__
__module____qualname____firstlineno____doc____static_attributes__r       Y/root/1688_scrapy/alibaba-scraper/venv/lib/python3.13/site-packages/twisted/python/log.pyr   r   %   s    r&   r   c                   *    \ rS rSrSrS\SS4S jrSrg)ILogObserver.   z
An observer which can do something with log events.

Given that most log observers are actually bound methods, it's okay to not
explicitly declare provision of this interface.
	eventDictreturnNc                     g)a  
Log an event.

@param eventDict: A dictionary with arbitrary keys.  However, these
    keys are often available:
      - C{message}: A C{tuple} of C{str} containing messages to be
        logged.
      - C{system}: A C{str} which indicates the "system" which is
        generating this event.
      - C{isError}: A C{bool} indicating whether this event represents
        an error.
      - C{failure}: A L{failure.Failure} instance
      - C{why}: Used as header of the traceback in case of errors.
      - C{format}: A string format used in place of C{message} to
        customize the event.  The intent is for the observer to format
        a message by doing something like C{format % eventDict}.
Nr   )r+   s    r'   __call__ILogObserver.__call__6       r&   r   )r    r!   r"   r#   r$   	EventDictr.   r%   r   r&   r'   r)   r)   .   s    I $ r&   r)   system-c                     [         R                  " [        5      R                  5       nUR	                  U 5        [         R
                  " [        U0U/UQ70 UD6$ N)r   getr   copyupdatecall)ctxfuncargskwnewCtxs        r'   callWithContextr?   M   sE    [[%**,F
MM#<<f-tAdAbAAr&   c                      U R                  5       n [	        SU0U/UQ70 UD6$ ! [         a    e [         a    Sn[        US9   N4f = f! [         a    e [         a    [        US9   gf = f)zy
Utility method which wraps a function in a try:/except:, logs a failure if
one occurs, and uses the system's logPrefix.
z(buggy logPrefix method))r2   r2   N)	logPrefixKeyboardInterruptBaseExceptionerrr?   )loggerr;   r<   r=   lps        r'   callWithLoggerrG   S   s    
"~tAdAbAA   '2
   2s    % A
 AA
A*)A*c                 2   U c  [         R                  " 5       n [        U [         R                  5      (       a  [        SXSS.UD6  g[        U [        5      (       a$  [        S[         R                  " U 5      USS.UD6  g[        [        U 5      4USS.UD6  g)a  
Write a failure to the log.

The C{_stuff} and C{_why} parameters use an underscore prefix to lessen
the chance of colliding with a keyword argument the application wishes
to pass.  It is intended that they be supplied with arguments passed
positionally, not by keyword.

@param _stuff: The failure to log.  If C{_stuff} is L{None} a new
    L{Failure} will be created from the current exception state.  If
    C{_stuff} is an C{Exception} instance it will be wrapped in a
    L{Failure}.
@type _stuff: L{None}, C{Exception}, or L{Failure}.

@param _why: The source of this failure.  This will be logged along with
    C{_stuff} and should describe the context in which the failure
    occurred.
@type _why: C{str}
N   )r   whyisError)rJ   rK   r   )r   Failure
isinstancemsg	Exceptionrepr)_stuff_whyr=   s      r'   rD   rD   g   sz    ( ~"&'//**6Fa626	FI	&	&GGOOF+qGBGDL4dA44r&   c                       \ rS rSrSrS rSrg)r      zE
This represents a class which may 'own' a log. Used by subclassing.
c                     g)z
Override this method to insert custom logging behavior.  Its
return value will be inserted in front of every line.  It may
be called more times than the number of output lines.
r3   r   selfs    r'   rA   Logger.logPrefix   s     r&   r   N)r    r!   r"   r#   r$   rA   r%   r   r&   r'   r   r      s    r&   r   c                   ^    \ rS rSrSrS/rSSS\4S jr\S 5       r	S r
S rS	 rS
 rS rSrg)r      z-
Class for singleton log message publishing.
rN   Nc                 l   Uc  [        5       nUc  UnUc
  [        5       nXl        X l        / U l        UcG  [        5       nUR	                  U5        [        U[        [        [        5       5      [        [        5      nX0l        X@l        UR                  U l        U R                  R                  U l        g r5   )NewPublisher_observerPublisher_publishPublisher_legacyObserversaddObserverr   r   r   NullFilesyswarnings_logBeginner_warningsModuleshowwarning_oldshowwarning)rW   observerPublisherpublishPublisherlogBeginnerwarningsModulebeginnerPublishers         r'   __init__LogPublisher.__init__   s     #+~ ($4!$ ,"3!1 " ,))*;<%!4(*#=sHK (--99,,88r&   c                 X    U R                    Vs/ s H  oR                  PM     sn$ s  snf )z
Property returning all observers registered on this L{LogPublisher}.

@return: observers previously added with L{LogPublisher.addObserver}
@rtype: L{list} of L{callable}
)r_   legacyObserver)rW   xs     r'   	observersLogPublisher.observers   s(     +/*?*?@*?Q  *?@@@s   'c                     [        U5      nU R                  R                  U5        U R                  R	                  U/SU5        g)z
Begin logging to the L{LogBeginner} associated with this
L{LogPublisher}.

@param other: the observer to log to.
@type other: L{LogBeginner}

@param setStdout: if true, send standard I/O to the observer as well.
@type setStdout: L{bool}
TN)r   r_   appendrd   beginLoggingTo)rW   other	setStdoutwrappeds       r'   _startLoggingLogPublisher._startLogging   s<     +51$$W-(('D)Dr&   c                     U R                   R                  U R                  :X  a  U R                  U R                   l        gg)z
Clean-up hook for fixing potentially global state.  Only for testing of
this module itself.  If you want less global state, use the new
warnings system in L{twisted.logger}.
N)re   rf   rg   rV   s    r'   _stopLoggingLogPublisher._stopLogging   s8     ++t/?/??/3/C/CD  , @r&   c                     [        U5      nU R                  R                  U5        U R                  R	                  U5        g)z
Add a new observer.

@type other: Provider of L{ILogObserver}
@param other: A callable object that will be called with each new log
    message (a dict).
N)r   r_   ru   r]   r`   )rW   rw   ry   s      r'   r`   LogPublisher.addObserver   s6     +51$$W-++G4r&   c                     U R                    HK  nUR                  U:X  d  M  U R                   R                  U5        U R                  R	                  U5          g   g)z
Remove an observer.
N)r_   rp   remover]   removeObserver)rW   rw   observers      r'   r   LogPublisher.removeObserver   sM     --H&&%/%%,,X6''66x@	 .r&   c                 (   [        [        [        R                  " [        5      =(       d    0 R                  5       5      nUR                  U5        XS'   [        R                  " 5       US'   SU;  a  SUS'   [        U R                  U[        5        g)a  
Log a new message.

The message should be a native string, i.e. bytes on Python 2 and
Unicode on Python 3. For compatibility with both use the native string
syntax, for example::

    >>> log.msg('Hello, world.')

You MUST avoid passing in Unicode on Python 2, and the form::

    >>> log.msg('Hello ', 'world.')

This form only works (sometimes) by accident.

Keyword arguments will be converted into items in the event
dict that is passed to L{ILogObserver} implementations.
Each implementation, in turn, can define keys that are used
by it specifically, in addition to common keys listed at
L{ILogObserver.__call__}.

For example, to set the C{system} parameter while logging
a message::

>>> log.msg('Started', system='Foo')

messagetimerK   r   N)r   r1   r   r6   r   r7   r8   r   _publishNewr^   textFromEventDict)rW   r   r=   actualEventDicts       r'   rN   LogPublisher.msg   sr    8 y7;;{+C+Ir*O*O*QRr"%,	""&))+O+)*OI&D**O=NOr&   )r_   rd   r]   rg   r^   re   rf   )r    r!   r"   r#   r$   synchronizedrc   rm   propertyrr   rz   r}   r`   r   rN   r%   r   r&   r'   r   r      sU     7L 98 A AED
5#Pr&   r   theLogPublisherc                    ^  U 4S jnU$ )a  
A decorator that returns its argument rather than the thing it is
decorating.

This allows the documentation generator to see an alias for a method or
constant as an object with a docstring and thereby document it and
allow references to it statically.

@param something: An object to create an alias for.
@type something: L{object}

@return: a 1-argument callable that returns C{something}
@rtype: L{object}
c                    > T$ r5   r   )thingWithADocstring	somethings    r'   decorate_actually.<locals>.decorate,  s	    r&   r   )r   r   s   ` r'   	_actuallyr     s     	 r&   )rh   ri   rj   c                     g)z
Add a log observer to the global publisher.

@see: L{LogPublisher.addObserver}

@param observer: a log observer
@type observer: L{callable}
Nr   r   s    r'   r`   r`   7  r0   r&   c                     g)z
Remove a log observer from the global publisher.

@see: L{LogPublisher.removeObserver}

@param observer: a log observer previously added with L{addObserver}
@type observer: L{callable}
Nr   r   s    r'   r   r   B  r0   r&   c                      g)a  
Publish a message to the global log publisher.

@see: L{LogPublisher.msg}

@param message: the log message
@type message: C{tuple} of L{str} (native string)

@param event: fields for the log event
@type event: L{dict} mapping L{str} (native string) to L{object}
Nr   )r   events     r'   rN   rN   M  r0   r&   c                      g)z_
Publish a Python warning through the global log publisher.

@see: L{LogPublisher.showwarning}
Nr   r   r&   r'   rf   rf   [  r0   r&   	fmtStringfmtDictr,   c                      X-  nU$ ! [          a    e [         a;    SU < SU< 3n U$ ! [         a    SU < S3n O! [         a    Sn  Of = ff = f U$ f = f)a  
Try to format a string, swallowing all errors to always return a string.

@note: For backward-compatibility reasons, this function ensures that it
    returns a native string, meaning L{bytes} in Python 2 and L{str} in
    Python 3.

@param fmtString: a C{%}-format string
@param fmtDict: string formatting arguments for C{fmtString}

@return: A native string, formatted from C{fmtString} and C{fmtDict}.
z>Invalid format string or unformattable object in log message: z, z-UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt z, MESSAGE LOSTzJPATHOLOGICAL ERROR IN BOTH FORMAT STRING AND MESSAGE DETAILS, MESSAGE LOST)rB   rC   )r   r   texts      r'   _safeFormatr   d  s    &"* K)   	 *3G=   K  
		 '02  ! 4 
	 K%sD    A
)
A<AAA	AAAAAr+   c                    U S   nU(       d  U S   (       a{  SU ;   au  [        [        U R                  S5      5      nU(       a  [        R                  " U5      nOSn [        [
        R                  U S   5      R                  5       nUS-   U-   nU$ S	U ;   a  [        U S	   U 5      nU$ gS
R                  [        [        R                  U5      5      nU$ ! [         a  nS[        U5      -   n SnANjSnAff = f)a  
Extract text from an event dict passed to a log observer. If it cannot
handle the dict, it returns None.

The possible keys of eventDict are:
 - C{message}: by default, it holds the final text. It's required, but can
   be empty if either C{isError} or C{format} is provided (the first
   having the priority).
 - C{isError}: boolean indicating the nature of the event.
 - C{failure}: L{failure.Failure} instance, required if the event is an
   error.
 - C{why}: if defined, used as header of the traceback in case of errors.
 - C{format}: string format used in place of C{message} to customize
   the event. It uses all keys present in C{eventDict} to format
   the text.
Other keys will be used when applying the C{format}, or ignored.
r   rK   r   rJ   zUnhandled Errorz(unable to obtain traceback): N
format )r   strr6   r   safe_strr   rL   getTracebackrO   r   joinmap)r+   edmrJ   	tracebacker   s         r'   r   r     s    $ I
CYI$:sIMM%01C&&s+'F )I2FGTTV	 :	)D K "y2I>D K xxG,,c23K  F<s1vE	Fs   +C 
C7C22C7c                   H    \ rS rSrSr\S\SS4S j5       rS
S jrS
S jr	S	r
g)_GlobalStartStopObserveri  z:
Mix-in for global log observers that can start and stop.
r+   r,   Nc                     g)z:
Emit the given log event.

@param eventDict: a log event
Nr   rW   r+   s     r'   emit_GlobalStartStopObserver.emit  r0   r&   c                 .    [        U R                  5        g)z
Start observing log events.
N)r`   r   rV   s    r'   start_GlobalStartStopObserver.start  s     	DIIr&   c                 .    [        U R                  5        g)z
Stop observing log events.
N)r   r   rV   s    r'   stop_GlobalStartStopObserver.stop  s     	tyy!r&   r   )r,   N)r    r!   r"   r#   r$   r   r1   r   r   r   r%   r   r&   r'   r   r     s3     i D  "r&   r   c                   R    \ rS rSr% SrSr\\   \S'   S r	S r
S rS\S	S4S
 jrSrg)FileLogObserveri  z
Log observer that writes to a file-like object.

@type timeFormat: C{str} or L{None}
@ivar timeFormat: If not L{None}, the format string passed to strftime().
N
timeFormatc                 H    UR                   U l         UR                  U l        g r5   )writeflush)rW   fs     r'   rm   FileLogObserver.__init__  s    WW
WW
r&   c                     [         R                  " U[        R                  5      R	                  SS9[         R                  " U5      -
  nUR
                  S-  UR                  -   $ )z
Return the current local timezone offset from UTC.

@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.

@rtype: C{int}
@return: The number of seconds offset from UTC.  West is positive,
east is negative.
NtzinfoiQ )r   fromtimestampr   utcreplacedaysseconds)rW   whenoffsets      r'   getTimezoneOffset!FileLogObserver.getTimezoneOffset  s[     ''hll;CC D 
""4() {{l+fnn<<r&   c           
         U R                   b/  [        R                  " U5      R                  U R                   5      $ U R	                  U5      * n[        R                  " X-   [
        R                  5      R                  SS9n[        [        US-  S-  5      5      n[        [        US-  S-  5      5      nUS:  a  SnOSnSUR                  UR                  UR                  UR                  UR                  UR                  UUU4	-  $ )a  
Format the given UTC value as a string representing that time in the
local timezone.

By default it's formatted as an ISO8601-like string (ISO8601 date and
ISO8601 time separated by a space). It can be customized using the
C{timeFormat} attribute, which will be used as input for the underlying
L{datetime.datetime.strftime} call.

@type when: C{int}
@param when: POSIX (ie, UTC) timestamp for which to find the offset.

@rtype: C{str}
Nr   <   r   r3   +z%%d-%02d-%02d %02d:%02d:%02d%s%02d%02d)r   r   r   strftimer   r   r   r   absintyearmonthdayhourminutesecond)rW   r   tzOffsettzHourtzMintzSigns         r'   
formatTimeFileLogObserver.formatTime  s     ??&))$/88II**400%%dox||DLL M 
 SB+,-C2*+,a<FF6IIJJHHIIKKKK
:
 

 
	
r&   r+   r,   c                     [        U5      nUc  gU R                  US   5      nUS   UR                  SS5      S.n[        SU5      n[        R
                  " U R                  US-   U-   5        [        R
                  " U R                  5        g)	zd
Format the given log event as text and write it to the output file.

@param eventDict: a log event
Nr   r2   r   z
	)r2   r   z[%(system)s] %(text)s
r   )r   r   r   r   r   untilConcludesr   r   )rW   r+   r   timeStrr   msgStrs         r'   r   FileLogObserver.emit  s     !+<//)F"34&x0$,,tV:TU6@DJJ#(>?DJJ'r&   )r   r   )r    r!   r"   r#   r$   r   r
   r   __annotations__rm   r   r   r1   r   r%   r   r&   r'   r   r     s:     !%J$
= &
P(i (D (r&   r   c                   4    \ rS rSrSrS	S jrS\SS4S jrSrg)
PythonLoggingObserveri,  a4  
Output twisted messages to Python standard library L{logging} module.

WARNING: specific logging configurations (example: network) can lead to
a blocking system. Nothing is done here to prevent that, so be sure to not
use this: code within Twisted, such as twisted.web, assumes that logging
does not block.
c                 $    [        U5      U l        g)zQ
@param loggerName: identifier used for getting logger.
@type loggerName: C{str}
N)NewSTDLibLogObserver_newObserver)rW   
loggerNames     r'   rm   PythonLoggingObserver.__init__6  s    
 1<r&   r+   r,   Nc                 H    SU;   a  [        U R                  U[        5        gg)a   
Receive a twisted log entry, format it and bridge it to python.

By default the logging level used is info; log.err produces error
level, and you can customize the level by using the C{logLevel} key::

    >>> log.msg('debugging', logLevel=logging.DEBUG)

log_formatN)r   r   r   r   s     r'   r   PythonLoggingObserver.emit=  s$     9$))96GH %r&   )r   )twisted)	r    r!   r"   r#   r$   rm   r1   r   r%   r   r&   r'   r   r   ,  s"    =
Ii 
ID 
Ir&   r   c                   f    \ rS rSrSrSrSrSrSrSS jr	S r
S	 rS
 rS r\r\r\r\rS rS rSrg)StdioOnnaStickiJ  a8  
Class that pretends to be stdout/err, and turns writes into log messages.

@ivar isError: boolean indicating whether this is stderr, in which cases
               log messages will be logged as errors.

@ivar encoding: unicode encoding used to encode any unicode strings
                written to this object.
r   wbz<stdio (log)>Nc                 Z    Xl         Uc  [        R                  " 5       nX l        SU l        g )N )rK   rb   getdefaultencodingencodingbuf)rW   rK   r   s      r'   rm   StdioOnnaStick.__init__Z  s'    --/H r&   c                     g r5   r   rV   s    r'   closeStdioOnnaStick.closea      r&   c                     g)Nr   rV   s    r'   filenoStdioOnnaStick.filenod  s    r&   c                     g r5   r   rV   s    r'   r   StdioOnnaStick.flushg  r   r&   c                     [        S5      e)Nzcan't read from the log!)OSErrorrV   s    r'   readStdioOnnaStick.readj  s    011r&   c                     U R                   U-   R                  S5      nUS   U l         USS nU H  n[        USU R                  S9  M     g )Nr   r   r   rI   printedrK   )r   splitrN   rK   )rW   datadmessagesr   s        r'   r   StdioOnnaStick.writer  sJ    XX_##D)R5Qr7GDLL9  r&   c                 @    U H  n[        USU R                  S9  M     g )NrI   r	  )rN   rK   )rW   lineslines      r'   
writelinesStdioOnnaStick.writelinesy  s    Da6 r&   )r   r   rK   )r   N)r    r!   r"   r#   r$   closed	softspacemodenamerm   r   r   r   r  readline	readlinesseektellr   r  r%   r   r&   r'   r   r   J  sV     FIDD2 HIDD:7r&   r   c                 z    [        U [        5      (       a  g[        U 5      n[        UR                  /UQ70 UD6  U$ )zt
Initialize logging to a specified file.

@return: A L{FileLogObserver} if a new observer is added, None otherwise.
N)rM   r   r   startLoggingWithObserverr   )filear=   flos       r'   startLoggingr"  ~  s9     $$$
$
CSXX00R0Jr&   c                 D    [         R                  X5        [        S5        g)z
Initialize logging to a specified observer. If setStdout is true
(defaults to yes), also redirect sys.stdout and sys.stderr
to the specified file.
zLog opened.N)r   rz   rN   )r   rx   s     r'   r  r    s     !!(6r&   c                   4    \ rS rSrSrSrS rS rS rS r	Sr
g	)
ra   i  z.
A file-like object that discards everything.
r   c                     gz
Do nothing.
Nr   rV   s    r'   r  NullFile.read  r0   r&   c                     g)z7
Do nothing.

@param bytes: data
@type bytes: L{bytes}
Nr   )rW   bytess     r'   r   NullFile.write  r0   r&   c                     gr&  r   rV   s    r'   r   NullFile.flush  r0   r&   c                     gr&  r   rV   s    r'   r   NullFile.close  r0   r&   r   N)r    r!   r"   r#   r$   r  r  r   r   r   r%   r   r&   r'   ra   ra     s"     I

r&   ra   c                      [        5       qg)z;
Discard messages logged via the global C{logfile} object.
N)ra   logfiler   r&   r'   discardLogsr1    s    
 jGr&   r0  r   )rE   levelr   c                   B    \ rS rSrSr\R                  rS\SS4S jrSr	g)DefaultObserveri  z
Default observer.

Will ignore all non-error messages and send error messages to sys.stderr.
Will be removed when startLogging() is called for the first time.
r+   r,   Nc                     US   (       aD  [        U5      nUb  U R                  R                  U5        U R                  R                  5         gg)z6
Emit an event dict.

@param eventDict: an event dict
rK   N)r   stderrr   r   )rW   r+   r   s      r'   r   DefaultObserver.emit  sC     Y$Y/D!!$'KK	  r&   r   )
r    r!   r"   r#   r$   rb   r6  r1   r   r%   r   r&   r'   r4  r4    s%     ZZF
 i 
 D 
 r&   r4  defaultObserver)NN)rI   )Or$   rb   r   rc   abcr   r   r   r   typingr   r   r	   r
   r   zope.interfacer   twisted.loggerr   r   	NewLoggerr   r   NewLogLevelr   r\   r   r   r   newGlobalLogBeginnerr   newGlobalLogPublishertwisted.logger._globalr   twisted.logger._legacyr   r   twisted.pythonr   r   r   r   twisted.python.threadabler   r   r1   r   r)   
setDefaultr?   rG   rD   deferrglobalsr   r   r`   r   rN   rf   r   r   r   r   r   r   r"  r  ra   r1  infogetattrstdoutr0  errorr6  logerrr4  r8  r   r&   r'   <module>rM     sg  

    # ' 6 6 $	 	 	 / F : : 1cN	 9 8   ;3 0B(5< 
 ~P ~PB L  GI%* #/.(O **+ , --. / ""# $ **+ ,)3 )c3h )C )X& &x} &R"s "4V(. V(rI4 I<17 17h
 > GI{Z6G
 {Z6F .  . GI%%'O &r&   