ϪfW dZddlZddlZddlZddlmZmZddlmZmZddl m Z m Z m Z m Z mZddlmZddlmZmZmZmZmZmZmZmZddl m!Z!dd l"m#Z$dd l%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+e e,e fZ-Gd d Z.GddeZ/e&j`e.ddidZ1dZ2d9dZ3e3Z4GddZGddZe+ede5vrndZ6eeeeZ7e6e7jpdZ8e6e7jrdZ9e6e7jtdZ:e6e7jvdZ;d e,d!e e,e fd"e,fd#ZGd(d)e>Z?Gd*d+e>Z@Gd,d-ZAd.ZBd:d/ZCGd0d1ZDd2ZEd3e5vrXeeejeGejd4d5aIeeejeGejd4d5ZLGd6d7e>ZMd8e5vreMZNyy);z% Logging and metrics infrastructure. N)ABCabstractmethod)datetimetimezone)AnyBinaryIODictOptionalcast) Interface)LegacyLogObserverWrapperLogger LoggingFileLogLevel LogPublisherSTDLibLogObserverglobalLogBeginnerglobalLogPublisher) LogBeginner)publishToNewObserver)contextfailurereflectutil) synchronizeceZdZdZy) ILogContextz 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____doc__4/usr/lib/python3/dist-packages/twisted/python/log.pyrr%sr#rc eZdZdZdeddfdZy) ILogObserverz 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. eventDictreturnNcy)a6 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__zILogObserver.__call__6r#)rrr r! EventDictr*r"r#r$r&r&.s I $ r#r&system-ctjtj}|j |tj t|i|g|i|SN)rgetrcopyupdatecall)ctxfuncargskwnewCtxs r$callWithContextr:MsE [[ % * * ,F MM# <<f-t Ad Ab AAr#c |j} t d|i|g|i|S#t$rt$rd}t|Y5wxYw#t$rt$rt|YywxYw)z 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))r-r-N) logPrefixKeyboardInterrupt BaseExceptionerrr:)loggerr6r7r8lps r$callWithLoggerrBSs      "~tAdAbAA   ' 2   2s %A AA A,+A,c |tj}t|tjrtd||dd|yt|tr#tdtj||dd|ytt |f|dd|y)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)rwhyisError)rErFr")rFailure isinstancemsg Exceptionrepr)_stuff_whyr8s r$r?r?gsv(~"&'//* 6Fa626 FI & GGOOF+qGBG DL4dA44r#ceZdZdZdZy)rzM This represents a class which may 'own' a log. Used by subclassing. cy)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. r.r"selfs r$r<zLogger.logPrefixs r#N)rrr r!r<r"r#r$rrs r#rcTeZdZdZdgZdddefdZedZdZ dZ dZ d Z d Z y) rz5 Class for singleton log message publishing. rINcl|t}||}| t}||_||_g|_|Gt}|j |t |t tttt}||_ ||_ |j|_|jj|_ yr0) NewPublisher_observerPublisher_publishPublisher_legacyObservers addObserverrr rNullFilesyswarnings _logBeginner_warningsModule showwarning_oldshowwarning)rQobserverPublisherpublishPublisher logBeginnerwarningsModulebeginnerPublishers r$__init__zLogPublisher.__init__s  #+~  ($4!  $ , "3!1 "   ,   ) )*; <%!4(*#=sHK(--99,,88r#cT|jDcgc]}|jc}Scc}w)z Property returning all observers registered on this L{LogPublisher}. @return: observers previously added with L{LogPublisher.addObserver} @rtype: L{list} of L{callable} )rWlegacyObserver)rQxs r$ observerszLogPublisher.observerss$+/*?*?@Q  @@@s%ct|}|jj||jj |gd|y)a& 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 rWappendr\beginLoggingTo)rQother setStdoutwrappeds r$ _startLoggingzLogPublisher._startLoggings<+51 $$W- (('D)Dr#c|jj|jk(r|j|j_yy)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)r]r^r_rPs r$ _stopLoggingzLogPublisher._stopLoggings8    + +t/?/? ?/3/C/CD , @r#ct|}|jj||jj |y)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 rWrkrUrX)rQrmros r$rXzLogPublisher.addObservers6+51 $$W- ++G4r#c|jD]I}|j|k(s|jj||jj |yy)z% Remove an observer. N)rWrgremoverUremoveObserver)rQrmobservers r$rvzLogPublisher.removeObserversR-- H&&%/%%,,X6''66x@  r#ctttjtxsij }|j |||d<tj|d<d|vrd|d<t|j|ty)ac 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') messagetimerFrN) r r,rr1rr2r3rz _publishNewrVtextFromEventDict)rQryr8actualEventDicts r$rIzLogPublisher.msgst8y7;;{+C+Ir*O*O*QRr"%, ""&))+ O +)*OI &D**O=NOr#)rrr r! synchronizedr[repropertyrirprrrXrvrIr"r#r$rrsU7L 98AA ED 5#Pr#rtheLogPublishercfd}|S)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} cSr0r")thingWithADocstring somethings r$decoratez_actually..decorate,s  r#r")rrs` r$ _actuallyrs  r#)r`rarbcy)z Add a log observer to the global publisher. @see: L{LogPublisher.addObserver} @param observer: a log observer @type observer: L{callable} Nr"rws r$rXrX7r+r#cy)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"rs r$rvrvBr+r#cy)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")ryevents r$rIrIMr+r#cy)zw Publish a Python warning through the global log publisher. @see: L{LogPublisher.showwarning} Nr"r"r#r$r^r^[r+r# fmtStringfmtDictr(c ||z}|S#t$rt$r5d|d|}Y|S#t$rd|d}n#t$rd}YnwxYwYY|SwxYwwxYw)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)r=r>)rrtexts r$ _safeFormatrds&7"* K)   *3G=  K  '02! 4  K  sD A& A 6A  AA AA A A  Ar'c|d}|s|drsd|vrott|jd}|rtj|}nd} tt j |dj}|dz|z}|Sd |vrt|d |}|Syd jttj|}|S#t$r}dt|z}Yd}~gd}~wwxYw) 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. ryrFrrEzUnhandled Errorz(unable to obtain traceback): N format ) r strr1rsafe_strrrG getTracebackrJrjoinmap)r'edmrE tracebackers r$r|r|s$ I C  Y I$:sIMM%01C&&s+' F )I2FGTTV : )D K "y2I>D KxxG,,c23 K F? DJJ'r#) rrr r!rr r__annotations__rerrr,rr"r#r$rrs:!%J $ = & P(i(D(r#rc(eZdZdZddZdeddfdZy)PythonLoggingObserveraL 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$t||_y)zi @param loggerName: identifier used for getting logger. @type loggerName: C{str} N)NewSTDLibLogObserver _newObserver)rQ loggerNames r$rezPythonLoggingObserver.__init__6s 1<r#r'r(NcDd|vrt|j|tyy)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{rr|rs r$rzPythonLoggingObserver.emit=s$ 9 $ ))96G H %r#)twisted)rrr r!rer,rr"r#r$rr,s"= Ii ID Ir#rc\eZdZdZdZdZdZdZd dZdZ dZ d Z d Z e Z e Ze Ze Zd Zd Zy)StdioOnnaStickaP 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. rwbz NcZ||_|tj}||_d|_y)N)rFrZgetdefaultencodingencodingbuf)rQrFrs r$rezStdioOnnaStick.__init__Zs+  --/H  r#cyr0r"rPs r$closezStdioOnnaStick.closea r#cy)Nr"rPs r$filenozStdioOnnaStick.filenodsr#cyr0r"rPs r$rzStdioOnnaStick.flushgrr#ctd)Nzcan't read from the log!)OSErrorrPs r$readzStdioOnnaStick.readjs011r#c|j|zjd}|d|_|dd}|D]}t|d|jy)NrrrrDprintedrF)rsplitrIrF)rQdatadmessagesrys r$rzStdioOnnaStick.writersO XX_ # #D )R5Qr7 :G DLL 9 :r#cB|D]}t|d|jy)NrDr)rIrF)rQlineslines r$ writelineszStdioOnnaStick.writelinesys! 7D a 6 7r#)rN)rrr r!closed softspacemodenamererrrrreadline readlinesseektellrrr"r#r$rrJsVFI D D  2HI D D:7r#rcpt|tryt|}t|jg|i||S)z Initialize logging to a specified file. @return: A L{FileLogObserver} if a new observer is added, None otherwise. N)rHrrstartLoggingWithObserverr)filear8flos r$ startLoggingr~s6 $ $ $ CSXX00R0 Jr#cFtj||tdy)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)rrprI)rwrns r$rrs !!(I6 r#c,eZdZdZdZdZdZdZdZy)rYz6 A file-like object that discards everything. rcyz Do nothing. Nr"rPs r$rz NullFile.readr+r#cy)zW Do nothing. @param bytes: data @type bytes: L{bytes} Nr")rQbytess r$rzNullFile.writer+r#cyrr"rPs r$rzNullFile.flushr+r#cyrr"rPs r$rzNullFile.closer+r#N) rrr r!rrrrrr"r#r$rYrYs"I    r#rYctay)zC Discard messages logged via the global C{logfile} object. N)rYlogfiler"r#r$ discardLogsr s jGr#r r)r@levelrc8eZdZdZej ZdeddfdZy)DefaultObserverz 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|drCt|}||jj||jjyy)zN Emit an event dict. @param eventDict: an event dict rFN)r|stderrrr)rQr'rs r$rzDefaultObserver.emitsC Y $Y/D !!$' KK    r#)rrr r!rZrr,rr"r#r$rrs%ZZF  i  D  r#rdefaultObserver)NN)rD)Or!rZrzr[abcrrrrtypingrrr r r zope.interfacer twisted.loggerr r NewLoggerrr NewLogLevelrrTrrrnewGlobalLogBeginnerrnewGlobalLogPublishertwisted.logger._globalrtwisted.logger._legacyrr{twisted.pythonrrrrtwisted.python.threadablerrr,rr& setDefaultr:rBr?deferrglobalsrrrXrvrIr^rr|rrrrrrrYr infogetattrstdoutr errorrlogerrrrr"r#r$r(si   #'66$   /F::1 cN  9 8;30B (5<   ~P~PB LGI%*#/.(O **+ , --. / ""#  $  **+ , )3)c3h)C)X&&x}&R"s"4V(.V(rI4I<1717h   > GI{Z6G {Z6F . .GI%%'O&r#