j f(@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl m Z dddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+g(Z yddl Z Wne k rdZ YnXd,Zd-Zd.Zd/ZejZd0Zd0Zd0Zd0Zd1ZeZd2Zd3ZeZd4Zd5ZdZide6de6de6de6de6de6Zied6ed6ed6ed6ed6ed6ed6Z d6d Z!d7dZ"e#ed8r(d9d:Z$n d;d<Z$ej%j&e"j'j(Z)d=d>Z*e rme j+Z,ndZ,d?d@Z-dAdBZ.GdCdde/Z0e0a1dDd*Z2dEd)Z3dFd%Z4GdGdHdHe/Z5GdIdJdJe5Z6GdKdLdLe5Z7dMZ8ie5e8fdN6e6dOfdP6e7dQfdR6Z9GdSd d e/Z:e:Z;GdTdde/Z<GdUd d e/Z=GdVdWdWe/Z>ej?Z@gZAdXdYZBdZd[ZCGd\d d e>ZDGd]ddeDZEGd^d d eEZFGd_d`d`eEZGeGeZHeHZIGdadbdbe/ZJdaKdcd&ZLddd"ZMGdedfdfe/ZNGdgdde>ZOGdhdidieOZPeOaKGdjdde/ZQePeZReReO_ReNeOjReO_SdkdZTddld!ZUdmdZVeVZWdndZXdodZYdpd(ZZdqd'Z[drd#Z\dsdZ]dtd$Z^dudZ_eAdvdwZ`ddlaZaeajbe`GdxddeDZcdaddddydzZed{dZfdS)|z Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2014 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! N)Template BASIC_FORMATBufferingFormatterCRITICALDEBUGERRORFATAL FileHandlerFilter FormatterHandlerINFO LogRecordLogger LoggerAdapterNOTSET NullHandler StreamHandlerWARNWARNING addLevelName basicConfigcaptureWarningscriticaldebugdisableerror exceptionfatal getLevelName getLoggergetLoggerClassinfolog makeLogRecordsetLoggerClasswarnwarninggetLogRecordFactorysetLogRecordFactory lastResortz&Vinay Sajip Z productionz0.5.1.2z07 February 2010T2( cCs tj|tj|d|S)a Return the textual representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string "Level %s" % level is returned. zLevel %s) _levelToNameget _nameToLevel)levelr45/opt/alt/python34/lib64/python3.4/logging/__init__.pyrvsc Cs.tz|t|<|t|sr;c Cs7y tWn&tk r2tjdjjSYnXdS)z5Return the frame object for the caller's stack frame.N) Exceptionr:exc_infotb_framef_backr4r4r4r5 currentframes  rAcCsjt|tr|}nNt||krV|tkrItd|nt|}ntd||S)NzUnknown level: %rz*Level not an integer or a valid string: %r) isinstanceintstrr2 ValueError TypeError)r3rvr4r4r5 _checkLevels   rHcCstrtjndS)z Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock(). N)_lockacquirer4r4r4r5r6sr6cCstrtjndS)zK Release the module-level lock acquired by calling _acquireLock(). N)rIreleaser4r4r4r5r7sr7c@s@eZdZdZddddZddZddZdS) ra A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged. Nc Ks0tj} ||_||_|rct|dkrct|dtjrc|drc|d}n||_t||_ ||_ ||_ y5t j j||_t j j|jd|_Wn-tttfk r||_d|_YnX||_d|_| |_||_||_| |_| t| d|_|jtd|_trt rt j!|_"t j#j|_$nd|_"d|_$t%sd|_&nUd|_&t'j(j)d} | dk ry| j*j|_&Wqt+k rYqXnt,r#t-t dr#t j.|_/n d|_/dS) zK Initialize a logging record with interesting information. rzUnknown moduleNiZ MainProcessZmultiprocessinggetpid)0timenamemsglenrB collectionsMappingargsrZ levelnamelevelnopathnameospathbasenamefilenamesplitextmodulerFrEAttributeErrorr>exc_text stack_infolinenoZfuncNamecreatedrCmsecs _startTimeZrelativeCreated logThreads threading get_identZthreadZcurrent_threadZ threadNamelogMultiprocessingZ processNamer:modulesr1Zcurrent_processr= logProcesseshasattrrMprocess) selfrOr3rVr`rPrTr>funcsinfokwargsctZmpr4r4r5__init__sR   .                    zLogRecord.__init__cCs&d|j|j|j|j|jfS)Nz!)rOrUrVr`rP)rlr4r4r5__str__;szLogRecord.__str__cCs,t|j}|jr(||j}n|S)z Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. )rDrPrT)rlrPr4r4r5 getMessage?s zLogRecord.getMessage)__name__ __module__ __qualname____doc__rqrrrsr4r4r4r5rs G cCs |adS)z Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. N)_logRecordFactory)factoryr4r4r5r)PscCstS)zH Return the factory to be used when instantiating a log record. )rxr4r4r4r5r(Zsc Cs5tdddddfdd}|jj||S)z Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. Nr)rx__dict__update)dictrGr4r4r5r$as!c@sFeZdZdZdZdZddZddZdd Zd S) PercentStylez %(message)sz %(asctime)sz %(asctime)cCs|p |j|_dS)N)default_format_fmt)rlfmtr4r4r5rqvszPercentStyle.__init__cCs|jj|jdkS)Nr)rfindasctime_search)rlr4r4r5usesTimeyszPercentStyle.usesTimecCs|j|jS)N)rr{)rlrecordr4r4r5format|szPercentStyle.formatN) rtrurvrasctime_formatrrqrrr4r4r4r5r~ps   r~c@s.eZdZdZdZdZddZdS)StrFormatStylez {message}z {asctime}z{asctimecCs|jj|jS)N)rrr{)rlrr4r4r5rszStrFormatStyle.formatN)rtrurvrrrrr4r4r4r5rs rc@sFeZdZdZdZdZddZddZddZd S) StringTemplateStylez ${message}z ${asctime}cCs(|p |j|_t|j|_dS)N)rrr_tpl)rlrr4r4r5rqszStringTemplateStyle.__init__cCs4|j}|jddkp3|j|jdkS)Nz$asctimer)rrr)rlrr4r4r5rs zStringTemplateStyle.usesTimecCs|jj|jS)N)rZ substituter{)rlrr4r4r5rszStringTemplateStyle.formatN) rtrurvrrrrqrrr4r4r4r5rs   rz"%(levelname)s:%(name)s:%(message)s%z{levelname}:{name}:{message}{z${levelname}:${name}:${message}$c@seZdZdZejZdddddZdZdZ ddd Z d d Z d d Z ddZ ddZddZdS)r a Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the default value of "%s(message)" is used. The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by: %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted NrcCsa|tkr.tddjtjnt|d||_|jj|_||_dS)a^ Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument (if omitted, you get the ISO8601 format). Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:`str.format` (``{}``) formatting or :class:`string.Template` formatting in your format string. .. versionchanged: 3.2 Added the ``style`` parameter. zStyle must be one of: %s,rN)_STYLESrEjoinkeys_stylerdatefmt)rlrrstyler4r4r5rqs   zFormatter.__init__z%Y-%m-%d %H:%M:%Sz%s,%03dcCs\|j|j}|r-tj||}n+tj|j|}|j||jf}|S)a Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. ) converterrarNZstrftimedefault_time_formatdefault_msec_formatrb)rlrrrpstr4r4r5 formatTimes zFormatter.formatTimecCsztj}|d}tj|d|d|d||j}|j|dddkrv|dd}n|S)z Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() r<rrLN r)ioStringIO tracebackprint_exceptiongetvalueclose)rlZeisiotbrr4r4r5formatExceptions  !  zFormatter.formatExceptioncCs |jjS)zK Check if the format uses the creation time of the record. )rr)rlr4r4r5rszFormatter.usesTimecCs|jj|S)N)rr)rlrr4r4r5 formatMessageszFormatter.formatMessagecCs|S)aU This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in. r4)rlr_r4r4r5 formatStacks zFormatter.formatStackcCs|j|_|jr6|j||j|_n|j|}|jrr|jsr|j |j|_qrn|jr|dddkr|d}n||j}n|j r|dddkr|d}n||j |j }n|S)az Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. rLNrrr) rsmessagerrrasctimerr>r^rr_r)rlrrr4r4r5r(s        zFormatter.format)rtrurvrwrNZ localtimerrqrrrrrrrrr4r4r4r5r s (     c@sIeZdZdZdddZddZddZd d ZdS) rzB A formatter suitable for formatting a number of records. NcCs|r||_n t|_dS)zm Optionally specify a formatter which will be used to format each individual record. N)linefmt_defaultFormatter)rlrr4r4r5rqQs zBufferingFormatter.__init__cCsdS)zE Return the header string for the specified records. rzr4)rlrecordsr4r4r5 formatHeader[szBufferingFormatter.formatHeadercCsdS)zE Return the footer string for the specified records. rzr4)rlrr4r4r5 formatFooteraszBufferingFormatter.formatFootercCsld}t|dkrh||j|}x$|D]}||jj|}q2W||j|}n|S)zQ Format the specified records and return the result as a string. rzr)rQrrrr)rlrrGrr4r4r5rgs zBufferingFormatter.format)rtrurvrwrqrrrr4r4r4r5rMs   c@s1eZdZdZdddZddZdS)r a Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed. rzcCs||_t||_dS)z Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. N)rOrQnlen)rlrOr4r4r5rqs zFilter.__init__cCse|jdkrdS|j|jkr)dS|jj|jd|jdkrQdS|j|jdkS)z Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. rTF.)rrOr)rlrr4r4r5filters$z Filter.filterN)rtrurvrwrqrr4r4r4r5r ws  c@sFeZdZdZddZddZddZdd Zd S) Filtererz[ A base class for loggers and handlers which allows them to share common code. cCs g|_dS)zE Initialize the list of filters to be an empty list. N)filters)rlr4r4r5rqszFilterer.__init__cCs&||jkr"|jj|ndS)z; Add the specified filter to this handler. N)rappend)rlrr4r4r5 addFilterszFilterer.addFiltercCs&||jkr"|jj|ndS)z@ Remove the specified filter from this handler. N)rremove)rlrr4r4r5 removeFilterszFilterer.removeFiltercCs[d}xN|jD]C}t|dr7|j|}n ||}|sd}PqqW|S)ag Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero. .. versionchanged: 3.2 Allow filters to be just callables. TrF)rrjr)rlrrGfresultr4r4r5rs  zFilterer.filterN)rtrurvrwrqrrrr4r4r4r5rs    rc Cs_ttt}}}|r[|r[|r[|z ||krL|j|nWd|XndS)zD Remove a handler reference from the internal cleanup list. N)r6r7 _handlerListr)wrrJrKhandlersr4r4r5_removeHandlerRefs rc Cs3tztjtj|tWdtXdS)zL Add a handler to the internal cleanup list using a weak reference. N)r6rrweakrefrefrr7)Zhandlerr4r4r5_addHandlerRefsrc@seZdZdZeddZddZddZeeeZ dd Z d d Z d d Z ddZ ddZddZddZddZddZddZddZdS)r aq Handler instances dispatch logging events to specific destinations. The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the 'raw' message as determined by record.message is logged. cCsFtj|d|_t||_d|_t||jdS)zz Initializes the instance - basically setting the formatter to None and the filter list to empty. N)rrq_namerHr3 formatterr createLock)rlr3r4r4r5rqs     zHandler.__init__cCs|jS)N)r)rlr4r4r5get_nameszHandler.get_namec CsRtz<|jtkr&t|j=n||_|rB|t|sz Handler.emitc CsE|j|}|rA|jz|j|Wd|jXn|S)a< Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission. N)rrJrrK)rlrrGr4r4r5handleHs  zHandler.handlecCs ||_dS)z5 Set the formatter for this handler. N)r)rlrr4r4r5 setFormatterZszHandler.setFormattercCsdS)z Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. Nr4)rlr4r4r5flush`sz Handler.flushc Cs?tz)|jr/|jtkr/t|j=nWdtXdS)a% Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. N)r6rrr7)rlr4r4r5ris z Handler.closecCsZtrVtjrVtj\}}}z"y tjjdtj|||dtjtjjd|j}x5|rtj j |j j t dkr|j}qrW|rtj|dtjn tjjd|j|jfy$tjjd|j|jfWn"tk r.tjjdYnXWntk rDYnXWd~~~XndS) aD Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. z--- Logging error --- Nz Call stack: rfilezLogged from file %s, line %s zMessage: %r Arguments: %s zwUnable to print the message and arguments - possible formatting error. Use the traceback above to help find the error. )raiseExceptionsr:stderrr>writerrr?rWrXdirnamef_code co_filename__path__r@ print_stackrZr`rPrTr=OSError)rlrrvrZframer4r4r5 handleErrorzs.         zHandler.handleErrorN)rtrurvrwrrqrrpropertyrOrrJrKrrrrrrrrr4r4r4r5r s         c@sCeZdZdZdZdddZddZdd ZdS) rz A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. rNcCs2tj||dkr%tj}n||_dS)zb Initialize the handler. If stream is not specified, sys.stderr is used. N)r rqr:rstream)rlrr4r4r5rqs   zStreamHandler.__init__c CsK|jz/|jr8t|jdr8|jjnWd|jXdS)z% Flushes the stream. rN)rJrrjrrK)rlr4r4r5rs  zStreamHandler.flushc CsiyC|j|}|j}|j||j|j|jWntk rd|j|YnXdS)a Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. N)rrr terminatorrr=r)rlrrPrr4r4r5rs    zStreamHandler.emit)rtrurvrwrrqrrr4r4r4r5rs  c@sOeZdZdZdddddZddZd d Zd d ZdS) r zO A handler class which writes formatted logging records to disk files. aNFcCsitjj||_||_||_||_|rOtj|d|_ nt j||j dS)zO Open the specified file and use it as the stream for logging. N) rWrXabspath baseFilenamemodeencodingdelayr rqrr_open)rlrZrrrr4r4r5rqs     zFileHandler.__init__cCs|jzezP|jr\z|jWd|j}d|_t|drX|jnXnWdtj|XWd|jXdS)z$ Closes the stream. Nr)rJrrrjrrrK)rlrr4r4r5rs    zFileHandler.closecCst|j|jd|jS)zx Open the current base file with the (original) mode and encoding. Return the resulting stream. r)openrrr)rlr4r4r5rszFileHandler._opencCs5|jdkr!|j|_ntj||dS)z Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. N)rrrr)rlrr4r4r5r szFileHandler.emit)rtrurvrwrqrrrr4r4r4r5r s   c@s7eZdZdZeddZeddZdS)_StderrHandlerz This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time. cCstj||dS)z) Initialize the handler. N)r rq)rlr3r4r4r5rqsz_StderrHandler.__init__cCstjS)N)r:r)rlr4r4r5r$sz_StderrHandler.streamN)rtrurvrwrrqrrr4r4r4r5rs rc@s.eZdZdZddZddZdS) PlaceHolderz PlaceHolder instances are used in the Manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API. cCsid|6|_dS)zY Initialize with the specified logger being a child of this placeholder. N) loggerMap)rlaloggerr4r4r5rq6szPlaceHolder.__init__cCs#||jkrd|j||tkr4t|ts4td|jq4n|adS)z Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() z(logger not derived from logging.Logger: N)r issubclassrFrt _loggerClass)klassr4r4r5r%Hs  cCstS)zB Return the class to be used when instantiating a logger. )rr4r4r4r5r!Usc@s^eZdZdZddZddZddZdd Zd d Zd d Z dS)Managerzt There is [under normal circumstances] just one Manager instance, which holds the hierarchy of loggers. cCs:||_d|_d|_i|_d|_d|_dS)zT Initialize the manager with the root node of the logger hierarchy. rFN)rootremittedNoHandlerWarning loggerDict loggerClasslogRecordFactory)rlZrootnoder4r4r5rqas      zManager.__init__c Csd}t|ts$tdntz||jkr|j|}t|tr|}|jpkt|}||_||j|<|j |||j |qn8|jpt|}||_||j|<|j |Wdt X|S)a Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. NzA logger name must be a string) rBrDrFr6rrrrmanager_fixupChildren _fixupParentsr7)rlrOrGphr4r4r5r ls(      zManager.getLoggercCsA|tkr4t|ts4td|jq4n||_dS)zY Set the class to be used when instantiating a logger with this Manager. z(logger not derived from logging.Logger: N)rrrFrtr)rlrr4r4r5r%s  zManager.setLoggerClasscCs ||_dS)zg Set the factory to be used when instantiating a log record with this Manager. N)r)rlryr4r4r5r)szManager.setLogRecordFactorycCs|j}|jd}d}x|dkr| r|d|}||jkrit||j|N)r)rlrPrTror4r4r5rs zLogger.exceptioncOs,|jtr(|jt|||ndS)z Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) N)rrr)rlrPrTror4r4r5r%s zLogger.criticalcOsWt|ts+tr$tdq+dSn|j|rS|j||||ndS)z Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) zlevel must be an integerN)rBrCrrFrr)rlr3rPrTror4r4r5r#3s z Logger.logFcCs t}|dk r!|j}nd }xt|dr|j}tjj|j}|tkrr|j}q*nd}|rt j }|j dt j |d||j}|d d kr|dd }n|jn|j|j|j|f}Pq*W|S) z Find the stack frame of the caller so that we can note the source file name, line number and function name. N(unknown file)r(unknown function)rzStack (most recent call last): rrLr)rrrNrr)rAr@rjrrWrXnormcaser_srcfilerrrrrrrf_linenoco_name)rlr_rrGcorZrnrr4r4r5 findCallerDs,          zLogger.findCallerNc Cst||||||||| } | dk rxP| D]E} | dksX| | jkrktd| n| | | j| rmextrarnrGkeyr4r4r5 makeRecordbs   zLogger.makeRecordc Csd}trRy|j|\}} } }Wqatk rNd\}} } YqaXnd\}} } |rt|tstj}qn|j|j||| |||| || } |j | dS)z Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. N(unknown file)r(unknown function))rrr)rrr) rr rErBtupler:r>rrOr) rlr3rPrTr>rr_rnr r rmrr4r4r5rqs z Logger._logcCs-|j r)|j|r)|j|ndS)z Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. N)rr callHandlers)rlrr4r4r5rsz Logger.handlec Cs<tz&||jkr,|jj|nWdtXdS)z; Add the specified handler to this logger. N)r6rrr7)rlhdlrr4r4r5 addHandlers zLogger.addHandlerc Cs<tz&||jkr,|jj|nWdtXdS)z@ Remove the specified handler from this logger. N)r6rrr7)rlrr4r4r5 removeHandlers zLogger.removeHandlercCsF|}d}x3|rA|jr(d}Pn|js5Pq|j}qW|S)a See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger which is checked for the existence of handlers. FT)rrr)rlrrGr4r4r5 hasHandlerss     zLogger.hasHandlerscCs|}d}xe|rsx=|jD]2}|d}|j|jkr|j|qqW|jsgd}q|j}qW|dkrtr|jtjkrtj|qqtr|jj rt j j d|j d|j_ qndS)a Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. rrLNz+No handlers could be found for logger "%s" T)rrUr3rrrr*rrrr:rrrO)rlrrfoundrr4r4r5rs$         zLogger.callHandlerscCs0|}x#|r+|jr|jS|j}q WtS)z Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. )r3rr)rlloggerr4r4r5getEffectiveLevels    zLogger.getEffectiveLevelcCs&|jj|krdS||jkS)z; Is this logger enabled for level 'level'? F)rrr)rlr3r4r4r5rszLogger.isEnabledForcCs:|j|k r*dj|j|f}n|jj|S)ab Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. r)rrrOrr )rlsuffixr4r4r5getChildszLogger.getChild)rtrurvrwrrqrrr"r'r&rrrrr#r rrrrrrrrrrr4r4r4r5rs.          c@s"eZdZdZddZdS) RootLoggerz A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. cCstj|d|dS)z= Initialize the logger with the name "root". rN)rrq)rlr3r4r4r5rq szRootLogger.__init__N)rtrurvrwrqr4r4r4r5rs rc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZdS)rzo An adapter for loggers which makes it easier to specify contextual information in logging output. cCs||_||_dS)ax Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) N)rr)rlrrr4r4r5rqs zLoggerAdapter.__init__cCs|j|d<||fS)a Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs. r)r)rlrPror4r4r5rk's zLoggerAdapter.processcOs|jt|||dS)zA Delegate a debug call to the underlying logger. N)r#r)rlrPrTror4r4r5r7szLoggerAdapter.debugcOs|jt|||dS)zA Delegate an info call to the underlying logger. N)r#r )rlrPrTror4r4r5r"=szLoggerAdapter.infocOs|jt|||dS)zC Delegate a warning call to the underlying logger. N)r#r)rlrPrTror4r4r5r'CszLoggerAdapter.warningcOs*tjdtd|j|||dS)Nz6The 'warn' method is deprecated, use 'warning' insteadr<)rr&rr')rlrPrTror4r4r5r&Is  zLoggerAdapter.warncOs|jt|||dS)zB Delegate an error call to the underlying logger. N)r#r)rlrPrTror4r4r5rNszLoggerAdapter.errorcOs$d|d<|jt|||dS)zF Delegate an exception call to the underlying logger. Tr>N)r#r)rlrPrTror4r4r5rTs zLoggerAdapter.exceptioncOs|jt|||dS)zD Delegate a critical call to the underlying logger. N)r#r)rlrPrTror4r4r5r[szLoggerAdapter.criticalcOsG|j|rC|j||\}}|jj||||ndS)z Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. N)rrkrr)rlr3rPrTror4r4r5r#aszLoggerAdapter.logcCs)|jjj|krdS||jkS)z; Is this logger enabled for level 'level'? F)rrrr)rlr3r4r4r5rjszLoggerAdapter.isEnabledForcCs|jj|dS)zC Set the specified level on the underlying logger. N)rr)rlr3r4r4r5rrszLoggerAdapter.setLevelcCs |jjS)zD Get the effective level for the underlying logger. )rr)rlr4r4r5rxszLoggerAdapter.getEffectiveLevelcCs |jjS)z@ See if the underlying logger has any handlers. )rr)rlr4r4r5r~szLoggerAdapter.hasHandlersN)rtrurvrwrqrkrr"r'r&rrrr#rrrrr4r4r4r5rs             c Ks*tzttjdkr|jdd}|dkrgd|krd|krtdqn'd|ksd|krtdn|dkr|jdd}|jdd }|rt||}n|jdd}t|}|g}n|jd d}|jd d }|tkrRtd dj tj n|jdt|d}t |||} x:|D]2}|j dkr|j | ntj|qW|jdd} | dk rtj| n|rdj |j } td| qnWdtXdS)a Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. rrNrrZz8'stream' and 'filename' should not be specified togetherzG'stream' or 'filename' should not be specified together with 'handlers'filemoderrrrzStyle must be one of: %srrrLr3z, zUnrecognised argument(s): %s)r6rQrrpoprEr rrrrr rrrrr7) rorrZrhrZdfsrZfsrr3rr4r4r5rsF4        cCs|rtjj|StSdS)z Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. N)rrr r)rOr4r4r5r scOs6ttjdkrtntj|||dS)z Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr)rPrTror4r4r5rs cOs6ttjdkrtntj|||dS)z Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr)rPrTror4r4r5rs cOsd|dN)r)rPrTror4r4r5rs cOs6ttjdkrtntj|||dS)z Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr')rPrTror4r4r5r's cOs'tjdtdt|||dS)Nz8The 'warn' function is deprecated, use 'warning' insteadr<)rr&rr')rPrTror4r4r5r&"s  cOs6ttjdkrtntj|||dS)z Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr")rPrTror4r4r5r"'s cOs6ttjdkrtntj|||dS)z Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr)rPrTror4r4r5r1s cOs9ttjdkrtntj||||dS)z Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. rN)rQrrrr#)r3rPrTror4r4r5r#;s cCs|tj_dS)zB Disable all logging calls of severity 'level' and below. N)rrr)r3r4r4r5rEscCsxt|ddD]}ye|}|rzAy"|j|j|jWnttfk rnYnXWd|jXnWqtrnYqXqWdS)z Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. N)reversedrJrrrrErKr)Z handlerListrr!r4r4r5shutdownKs    r#c@s:eZdZdZddZddZddZdS) ra This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package. cCsdS)zStub.Nr4)rlrr4r4r5ryszNullHandler.handlecCsdS)zStub.Nr4)rlrr4r4r5r|szNullHandler.emitcCs d|_dS)N)r)rlr4r4r5rszNullHandler.createLockN)rtrurvrwrrrr4r4r4r5ros   cCs|dk r7tdk rt||||||qnStj|||||}td}|jsz|jtn|jd|dS)a Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. Nz py.warningsz%s)_warnings_showwarningr formatwarningr rrrr')rcategoryrZr`rlinerrr4r4r5 _showwarnings    r(cCsL|r*tdkrHtjatt_qHntdk rHtt_dandS)z If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. N)r$r showwarningr()Zcapturer4r4r5rs    )grwr:rWrNrrrrrRstringr__all__re ImportError __author__Z __status__ __version__Z__date__rcrrdrgrirrrrrr rrr0r2rrrjrArXr__code__rrrHrrIr6r7objectrrxr)r(r$r~rrrrr rrr rWeakValueDictionaryrrrrr rr rZ_defaultLastResortr*rrr%r!rrrrrrrr rrrrr'r&r"rr#rr#atexitregisterrr$r(rr4r4r4r5s`           g      *%4   3>  l> q   b