o bW@sdZddlZddlZddlZddlmZmZddlmZddlm Z m Z m Z m Z m Z ddlmZddlmZmZmZmZmZmZmZmZddlm 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 d Z-GdddeZ.e%/e-ddiddZ0ddZ1dGddZ2e2Z3GdddZGdddZe*ede4vrddZ5eeeedZ6e5e6j7d d!Z7e5e6j8d"d#Z8e5e6j9d$d%Z9e5e6j:d&d'Z:d(e+d)e e+e fd*e+fd+d,Z;d-e,d*e e+fd.d/ZGd4d5d5e=Z?Gd6d7d7Z@d8d9ZAdHd;d<ZBGd=d>d>ZCd?d@ZDdAe4vrCeeejEeFejGdBddCaHeeejIeFejJdBddCZKGdDdEdEe=ZLdFe4vrVeLZMdSdS)Iz% Logging and metrics infrastructure. N)ABCabstractmethod)datetime)AnyBinaryIODictOptionalcast) Interface)LegacyLogObserverWrapperLogger LoggingFileLogLevel LogPublisherSTDLibLogObserverglobalLogBeginnerglobalLogPublisher) LogBeginner)publishToNewObserver)contextfailurereflectutil) synchronizec@seZdZdZdS) 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__rr4/usr/lib/python3/dist-packages/twisted/python/log.pyr%src@s"eZdZdZdeddfddZdS) 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. eventDictreturnNcCdS)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"rrr __call__6zILogObserver.__call__)rrrr EventDictr%rrrr r!.sr!system-cOs6tt}||tjt|i|g|Ri|SN)rgetrcopyupdatecall)ctxfuncargskwnewCtxrrr callWithContextMs r4cOsz|}Wntytyd}t|dYnwztd|i|g|Ri|WSty5tyCt|dYdSw)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 BaseExceptionerrr4)loggerr0r1r2lprrr callWithLoggerSs     r;cKs~|durt}t|tjrtd||dd|dSt|tr0tdt||dd|dStt|f|dd|dS)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)r=r>r)rFailure isinstancemsg Exceptionrepr)_stuff_whyr2rrr r8gs   r8c@seZdZdZddZdS)r zM This represents a class which may 'own' a log. Used by subclassing. cCr$)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)rselfrrr r5szLogger.logPrefixN)rrrrr5rrrr r s r c@s\eZdZdZdgZdddefddZeddZdd Z d d Z d d Z ddZ ddZ dS)rz5 Class for singleton log message publishing. rANcCs|dur t}|dur |}|durt}||_||_g|_|dur4t}||t|tttt t }||_ ||_ |j |_|j j |_ dSr*) NewPublisher_observerPublisher_publishPublisher_legacyObservers addObserverrr rNullFilesyswarnings _logBeginner_warningsModule showwarning_oldshowwarning)rGobserverPublisherpublishPublisher logBeginnerwarningsModulebeginnerPublisherrrr __init__s& zLogPublisher.__init__cCsdd|jDS)z Property returning all observers registered on this L{LogPublisher}. @return: observers previously added with L{LogPublisher.addObserver} @rtype: L{list} of L{callable} cSsg|]}|jqSr)legacyObserver).0xrrr sz*LogPublisher.observers..)rKrFrrr observersszLogPublisher.observerscCs*t|}|j||j|gd|dS)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 rKappendrPbeginLoggingTo)rGother setStdoutwrappedrrr _startLoggings zLogPublisher._startLoggingcCs |jj|jkr|j|j_dSdS)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)rQrRrSrFrrr _stopLoggingszLogPublisher._stopLoggingcCs$t|}|j||j|dS)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 rKr_rIrL)rGrarcrrr rLs zLogPublisher.addObservercCs8|jD]}|j|kr|j||j|dSqdS)z% Remove an observer. N)rKrZremoverIremoveObserver)rGraobserverrrr rgs    zLogPublisher.removeObservercOsXttttpi}||||d<t|d<d|vr#d|d<t|j |t dS)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') messagetimer>rN) r r'rr+rr,r-rj _publishNewrJtextFromEventDict)rGrir2actualEventDictrrr rAs  zLogPublisher.msg)rrrr synchronizedrOrYpropertyr^rdrerLrgrArrrr rs     rtheLogPublishercsfdd}|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} csSr*r)thingWithADocstring somethingrr decorate,z_actually..decorater)rsrtrrrr _actuallys rv)rTrUrVcCr$)z Add a log observer to the global publisher. @see: L{LogPublisher.addObserver} @param observer: a log observer @type observer: L{callable} Nrrhrrr rL7r&rLcCr$)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} Nrrwrrr rgBr&rgcOr$)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)rieventrrr rAMr&rAcCr$)zw Publish a Python warning through the global log publisher. @see: L{LogPublisher.showwarning} Nrrrrr rR[r&rR fmtStringfmtDictr#cCsz||}W|StytyBz d||f}WY|StyAzd|f}Wn ty8d}YnwYY|SYY|Sww)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}. zDInvalid format string or unformattable object in log message: %r, %sz=UNFORMATTABLE OBJECT WRITTEN TO LOG with fmt %r, MESSAGE LOSTzJPATHOLOGICAL ERROR IN BOTH FORMAT STRING AND MESSAGE DETAILS, MESSAGE LOST)r6r7)ryrztextrrr _safeFormatds8      r|r"c Cs|d}|s\|drMd|vrMtt|d}|rt|}nd}z ttj|d}WntyD}z dt|}WYd}~nd}~ww|d|}|Sd |vrZt |d |}|SdSd t tj|}|S) 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. rir>rr=zUnhandled Errorz(unable to obtain traceback): N format ) r strr+rsafe_strrr? getTracebackrBr|joinmap)r"edmr= tracebacker{rrr rls*  rlc@s:eZdZdZededdfddZd ddZd d d ZdS) _GlobalStartStopObserverzB Mix-in for global log observers that can start and stop. r"r#NcCr$)zR Emit the given log event. @param eventDict: a log event NrrGr"rrr emitr&z_GlobalStartStopObserver.emitcCt|jdS)z- Start observing log events. N)rLrrFrrr startz_GlobalStartStopObserver.startcCr)z, Stop observing log events. N)rgrrFrrr stoprz_GlobalStartStopObserver.stop)r#N) rrrrrr'rrrrrrr rs  rc@sLeZdZUdZdZeeed<ddZddZ dd Z d e d dfd d Z dS)FileLogObserverz 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 timeFormatcCs|j|_|j|_dSr*)writeflush)rGfrrr rYs zFileLogObserver.__init__cCs$t|t|}|jd|jS)a* 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. iQ)rutcfromtimestamp fromtimestampdaysseconds)rGwhenoffsetrrr getTimezoneOffsets z!FileLogObserver.getTimezoneOffsetc Cs|jdurt||jS|| }t||}tt|dd}tt|dd}|dkr6d}nd}d|j|j |j |j |j |j |||f S)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} N<rr)+z%%d-%02d-%02d %02d:%02d:%02d%s%02d%02d)rrrstrftimerrabsintyearmonthdayhourminutesecond)rGrtzOffsettzHourtzMintzSignrrr formatTimes(  zFileLogObserver.formatTimer"r#cCsht|}|dur dS||d}|d|ddd}td|}t|j|d|t|jdS) z| Format the given log event as text and write it to the output file. @param eventDict: a log event Nrjr(r}z )r(r{z[%(system)s] %(text)s r)rlrreplacer|runtilConcludesrr)rGr"r{timeStrrzmsgStrrrr rs zFileLogObserver.emit) rrrrrrr__annotations__rYrrr'rrrrr rs &rc@s,eZdZdZd ddZdeddfdd ZdS) 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. twistedcCst||_dS)zi @param loggerName: identifier used for getting logger. @type loggerName: C{str} N)NewSTDLibLogObserver _newObserver)rG loggerNamerrr rY2szPythonLoggingObserver.__init__r"r#NcCsd|vr t|j|tdSdS)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)rkrrlrrrr r9s zPythonLoggingObserver.emit)r)rrrrrYr'rrrrr r(s rc@sjeZdZdZdZdZdZdZdddZdd Z d d Z d d Z ddZ e Z e Ze Ze ZddZddZdS)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 NcCs&||_|dur t}||_d|_dS)N)r>rNgetdefaultencodingencodingbuf)rGr>rrrr rYVs  zStdioOnnaStick.__init__cCdSr*rrFrrr close]ruzStdioOnnaStick.closecCr$)NrrFrrr fileno`ruzStdioOnnaStick.filenocCrr*rrFrrr rcruzStdioOnnaStick.flushcCstd)Nzcan't read from the log!)OSErrorrFrrr readfszStdioOnnaStick.readcCsD|j|d}|d|_|dd}|D] }t|d|jdqdS)Nr}rrr<printedr>)rsplitrAr>)rGdatadmessagesrirrr rns   zStdioOnnaStick.writecCs|D] }t|d|jdqdS)Nr<r)rAr>)rGlineslinerrr writelinesuszStdioOnnaStick.writelines)rN)rrrrclosed softspacemodenamerYrrrrreadline readlinesseektellrrrrrr rFs"   rcOs2t|trdSt|}t|jg|Ri||S)z Initialize logging to a specified file. @return: A L{FileLogObserver} if a new observer is added, None otherwise. N)r@r rstartLoggingWithObserverr)filear2florrr startLoggingzs rr<cCst||tddS)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)rprdrA)rhrbrrr rs  rc@s4eZdZdZdZddZddZddZd d Zd S) rMz6 A file-like object that discards everything. rcCr$z Do nothing. NrrFrrr rr&z NullFile.readcCr$)zW Do nothing. @param bytes: data @type bytes: L{bytes} Nr)rGbytesrrr rr&zNullFile.writecCr$rrrFrrr rr&zNullFile.flushcCr$rrrFrrr rr&zNullFile.closeN) rrrrrrrrrrrrr rMs rMcCs tadS)zC Discard messages logged via the global C{logfile} object. N)rMlogfilerrrr discardLogss rrr)r9levelrc@s(eZdZdZejZdeddfddZdS)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#NcCs6|drt|}|dur|j||jdSdS)zN Emit an event dict. @param eventDict: an event dict r>N)rlstderrrr)rGr"r{rrr rs  zDefaultObserver.emit)rrrrrNrr'rrrrr rsrdefaultObserver)NN)r<)NrrNrjrOabcrrrtypingrrrrr zope.interfacer twisted.loggerr r NewLoggerr r NewLogLevelrrHrrrnewGlobalLogBeginnerrnewGlobalLogPublishertwisted.logger._globalrtwisted.logger._legacyrrktwisted.pythonrrrrtwisted.python.threadablerrr'rr! setDefaultr4r;r8deferrglobalsrvrprLrgrArRr|rlrrrrrrrMrinfogetattrstdoutrerrorrlogerrrrrrrr s  (          ,)U4