a DOg@sNdZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z m Z dZ ejZdad+ddZdd Zd d Zd d ZddZddZddZddZedejZddZGdddeZGdddeeZ Gddde!eZ"Gdd d e#eZ$Gd!d"d"eZ%Gd#d$d$e%Z&e&Z'd%d&Z(e dfd'd(Z)d)d*Z*dS),a Configuration functions for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! N)ThreadingTCPServerStreamRequestHandleriF#TcCsddl}t||jr|}n*||}t|dr:||n ||t|}t z(t t ||}t |||Wt n t 0dS)aD Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). rNreadline) configparser isinstanceZRawConfigParser ConfigParserhasattrZ read_fileread_create_formatterslogging _acquireLock_clearExistingHandlers_install_handlers_install_loggers _releaseLock)fnamedefaultsdisable_existing_loggersrcp formattershandlersr&/usr/lib64/python3.9/logging/config.py fileConfig3s       rc Csj|d}|d}t|}|D]D}|d|}zt||}Wq tybt|t||}Yq 0q |S)z)Resolve a dotted name to a global object..r)splitpop __import__getattrAttributeError)nameusedfoundnrrr_resolveUs    r$cCs ttj|SN)mapstrstrip)Zalistrrr _strip_spacescsr)c Cs|dd}t|siS|d}t|}i}|D]v}d|}|j|dddd}|j|d ddd}|j|d dd d}tj}||d } | rt| }||||} | ||<q2|S) zCreate and return formattersrkeys,z formatter_%sformatTN)rawfallbackdatefmtstyle%class)lenrr)getr Formatterr$) rflistrZformZsectnamefsdfsZstlc class_namefrrrr fs$    r c Csh|dd}t|siS|d}t|}i}g}|D] }|d|}|d}|dd}zt|tt}Wnttfyt |}Yn0|dd } t| tt} |d d } t| tt} || i| } || _ d |vr|d } | | t|r| ||t |tjjr<|d d} t| r<|| | f| ||<q6|D]\} }| ||qJ|S)zInstall and return handlersrr*r+z handler_%sr2 formatterargs()kwargsz{}leveltarget)r3rr)r4evalvarsr r NameErrorr$r setLevel setFormatter issubclassr MemoryHandlerappendZ setTarget)rrhlistrZfixupshandsectionklassfmtr>r@hrArBtrrrr|sD             rcCsTtj}|D]D}|jj|}||vrHt|tjsN|tjg|_d|_ q ||_ q dS)a When (re)configuring logging, handle loggers which were in the previous configuration but are not in the new configuration. There's no point deleting them as other threads may continue to hold references to them; and by disabling them, you stop them doing any logging. However, don't disable children of named loggers, as that's probably not what was intended by the user. Also, allow existing loggers to NOT be disabled if disable_existing is false. TN) r rootmanager loggerDictr PlaceHolderrFNOTSETr propagatedisabled)existing child_loggersdisable_existingrRlogloggerrrr_handle_existing_loggerss    r^cCs |dd}|d}tt|}|d|d}tj}|}d|vrX|d}|||jddD]}||qf|d} t | r| d} t| } | D]} | || qt|j j } | g} |D](}|d |}|d } |jd d d }t| }| | vrv| | d }| d}t |}t | }||krl| |d||kr`| | ||d 7}q2| | d|vr|d}|||jddD]}||q||_d|_|d} t | r| d} t| } | D]} | || qqt| | |dS)zCreate and install loggersloggersr*r+rRZ logger_rootrANrz logger_%squalnamerW)r.rr)rlistr)remover rRrFr removeHandlerr3 addHandlerrSrTr*sortZgetint getLoggerindexrJrWrXr^)rrr[ZllistrMrRr\rArPrKrLrYrZZqnrWr]iprefixedpflen num_existingrrrrsd                  rcCs.tjttjddtjdd=dS)z!Clear and close existing handlersN)r _handlersclearshutdown _handlerListrrrrr s r z^[a-z_][a-z0-9_]*$cCst|}|std|dS)Nz!Not a valid Python identifier: %rT) IDENTIFIERmatch ValueError)smrrr valid_idents  rvc@s"eZdZdZdddZddZdS) ConvertingMixinz?For ConvertingXXX's, this mixin class provides common functionsTcCsB|j|}||ur>|r |||<t|tttfvr>||_||_|Sr%) configuratorconverttypeConvertingDictConvertingListConvertingTupleparentkey)selfrvaluereplaceresultrrrconvert_with_key#s  z ConvertingMixin.convert_with_keycCs0|j|}||ur,t|tttfvr,||_|Sr%)rxryrzr{r|r}r~)rrrrrrry/s  zConvertingMixin.convertN)T)__name__ __module__ __qualname____doc__rryrrrrrw s rwc@s,eZdZdZddZd ddZd ddZdS) r{z A converting dictionary wrapper.cCst||}|||Sr%)dict __getitem__rrrrrrrrDs zConvertingDict.__getitem__NcCst|||}|||Sr%)rr4rrrdefaultrrrrr4HszConvertingDict.getcCst|||}|j||ddSNF)r)rrrrrrrrLszConvertingDict.pop)N)N)rrrrrr4rrrrrr{As r{c@s"eZdZdZddZdddZdS) r|zA converting list wrapper.cCst||}|||Sr%)rbrrrrrrrRs zConvertingList.__getitem__cCst||}||Sr%)rbrry)ridxrrrrrVs zConvertingList.popN)r)rrrrrrrrrrr|Psr|c@seZdZdZddZdS)r}zA converting tuple wrapper.cCst||}|j||ddSr)tuplerrrrrrr\s zConvertingTuple.__getitem__N)rrrrrrrrrr}Zsr}c@seZdZdZedZedZedZedZ edZ ddd Z e e Zd d Zd d ZddZddZddZddZddZdS)BaseConfiguratorzI The configurator base class which defines some useful defaults. z%^(?P[a-z]+)://(?P.*)$z ^\s*(\w+)\s*z^\.\s*(\w+)\s*z^\[\s*(\w+)\s*\]\s*z^\d+$ ext_convert cfg_convert)extZcfgcCst||_||j_dSr%)r{configrx)rrrrr__init__us zBaseConfigurator.__init__c Cs|d}|d}z\||}|D]F}|d|7}zt||}Wq$tyh||t||}Yq$0q$|WStytdd\}}td||f}|||_ |_ |Yn0dS)z` Resolve strings to objects using standard import and attribute syntax. rrraNzCannot resolve %r: %s) rrimporterrr ImportErrorsysexc_infors __cause__ __traceback__) rrtr r!r"fragetbvrrrresolveys"       zBaseConfigurator.resolvecCs ||S)z*Default converter for the ext:// protocol.)rrrrrrrszBaseConfigurator.ext_convertcCs|}|j|}|dur&td|n||d}|j|d}|r|j|}|rn||d}nb|j|}|r|d}|j|s||}n0zt |}||}Wnt y||}Yn0|r||d}qHtd||fqH|S)z*Default converter for the cfg:// protocol.NzUnable to convert %rrzUnable to convert %r at %r) WORD_PATTERNrrrsendrgroups DOT_PATTERN INDEX_PATTERN DIGIT_PATTERNint TypeError)rrrestrudrr#rrrrs4        zBaseConfigurator.cfg_convertcCst|ts$t|tr$t|}||_nt|tsHt|trHt|}||_nt|tsvt|trvt|dsvt|}||_nVt|t r|j |}|r| }|d}|j |d}|r|d}t||}||}|S)z Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. _fieldsprefixNsuffix)rr{rrxr|rbr}rrr'CONVERT_PATTERNrr groupdictvalue_convertersr4r)rrrurr converterrrrrrys0    zBaseConfigurator.convertcsnd}t|s||}dd}fddD}|fi|}|rj|D]\}}t|||qT|S)z1Configure an object with a user-supplied factory.r?rNcsi|]}t|r||qSrrv.0krrr z5BaseConfigurator.configure_custom..)rcallableritemssetattr)rrr9propsr@rr rrrrconfigure_customs   z!BaseConfigurator.configure_customcCst|trt|}|S)z0Utility function which converts lists to tuples.)rrbrrrrras_tuples zBaseConfigurator.as_tupleN)rrrrrecompilerrrrrr staticmethodrrrrrrryrrrrrrras"     "rc@s^eZdZdZddZddZddZdd Zd d Zd d Z dddZ dddZ dddZ dS)DictConfiguratorz] Configure logging using a dictionary-like object to describe the configuration. c Cs|j}d|vrtd|ddkr2td|d|dd}i}tz|r|d|}|D]}|tjvrtd|qdz6tj|}||}|d d }|r|t|Wqdt y} ztd || WYd } ~ qdd } ~ 00qd|d |} | D]P}z| || |d Wqt yJ} ztd|| WYd } ~ qd } ~ 00q|dd } | rz| | d Wn0t y} ztd| WYd } ~ n d } ~ 00n$|dd } t |d|} | D]R}z| | || |<Wn4t y} ztd|| WYd } ~ n d } ~ 00q|d|}|D]R}z|||||<Wn4t yz} ztd|| WYd } ~ n d } ~ 00q,|d|}g}t|D]x}z |||}||_|||<WnPt y } z6dt| jvr||ntd || WYd } ~ n d } ~ 00q|D]\}z |||}||_|||<Wn4t yn} ztd || WYd } ~ n d } ~ 00qtj} t| jj}|g}|d |} | D]}||vr||d}|d}t|}t|}||kr||d ||kr||||d7}q||z| || |Wn4t yf} ztd|| WYd } ~ n d } ~ 00qt||| |dd } | rz| | Wn0t y} ztd| WYd } ~ n d } ~ 00Wtn t0d S)zDo the configuration.versionz$dictionary doesn't specify a versionrazUnsupported version: %s incrementalFrzNo handler found with name %rrANzUnable to configure handler %rr_TzUnable to configure logger %rrRzUnable to configure root loggerrrz Unable to configure formatter %rfilterszUnable to configure filter %rtarget not configured yetr) rrsrr r r4rmrF _checkLevel Exceptionconfigure_loggerconfigure_rootr configure_formatterconfigure_filtersortedconfigure_handlerr r'rrJrRrbrSrTr*rfrhr3rcr^r)rrr EMPTY_DICTrr handlerZhandler_configrArr_rRr[rrZdeferredrYrZrirjrkrlrrr configures                        zDictConfigurator.configurec Csd|vrt|d}z||}Wqtyp}z:dt|vr<|d|d<||d<||}WYd}~qd}~00nl|dd}|dd}|dd}|d d}|stj} nt|} d |vr| ||||d }n | |||}|S) z(Configure a formatter from a dictionary.r?z'format'r,rONr/r0r1r2validate)rrr'rr4r r5r$) rrfactoryrterOZdfmtr0cnamer9rrrrs* "     z$DictConfigurator.configure_formattercCs.d|vr||}n|dd}t|}|S)z%Configure a filter from a dictionary.r?r r=)rr4r Filter)rrrr rrrrs    z!DictConfigurator.configure_filterc CsZ|D]P}z||jd|WqtyR}ztd||WYd}~qd}~00qdS)z/Add filters to a filterer from a list of names.rzUnable to add filter %rN) addFilterrrrs)rZfiltererrr;rrrr add_filterss zDictConfigurator.add_filtersc st}dd}|r^z|jd|}Wn2ty\}ztd||WYd}~n d}~00dd}dd}dvrd}t|s||}|}nd} || } t| tj j rJd vrJz>|jd d } t | tj s |td | d <Wn8tyF}ztd d |WYd}~n d}~00nZt| tj jrxd vrx|d d <n,t| tj jrdvr|dd<| }dd} fddD} z|fi| }WnRty*}z8dt|vr| d| d<|fi| }WYd}~n d}~00|r<|||durV|t||rh|||| r| D]\}}t|||qv|S)z&Configure a handler from a dictionary.r<NrzUnable to set formatter %rrArr?r2rBrrzUnable to set target handler %rZmailhostaddressrcsi|]}t|r||qSrrrrrrrrz6DictConfigurator.configure_handler..z'stream'streamZstrm)rrrrrsrrrHr rrIrHandlerupdaterZ SMTPHandlerrZ SysLogHandlerr'rGrFrrrr)rrZ config_copyr<rrArr9rrrNthrr@rrr rrrrrs~          $   z"DictConfigurator.configure_handlerc CsZ|D]P}z||jd|WqtyR}ztd||WYd}~qd}~00qdS)z.Add handlers to a logger from a list of names.rzUnable to add handler %rN)rerrrs)rr]rrPrrrr add_handlerss zDictConfigurator.add_handlersFcCs|dd}|dur$|t||s~|jddD]}||q6|dd}|rb||||dd}|r~|||dS)zU Perform configuration which is common to root and non-root loggers. rANrr)r4rFr rrrdrr)rr]rrrArPrrrrrcommon_logger_configs     z%DictConfigurator.common_logger_configcCs6t|}|||||dd}|dur2||_dS)z.Configure a non-root logger from a dictionary.rWN)r rgrr4rW)rr rrr]rWrrrrs   z!DictConfigurator.configure_loggercCst}||||dS)z*Configure a root logger from a dictionary.N)r rgr)rrrrRrrrr szDictConfigurator.configure_rootN)F)F)F) rrrrrrrrrrrrrrrrrrs$ ?  rcCst|dS)z%Configure logging using a dictionary.N)dictConfigClassrrrrr dictConfig'srcsDGdddt}Gdddt}Gfdddtj||||S)au Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). Returns a Thread object on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening(). Use the ``verify`` argument to verify any bytes received across the wire from a client. If specified, it should be a callable which receives a single argument - the bytes of configuration data received across the network - and it should return either ``None``, to indicate that the passed in bytes could not be verified and should be discarded, or a byte string which is then passed to the configuration machinery as normal. Note that you can return transformed bytes, e.g. by decrypting the bytes passed in. c@seZdZdZddZdS)z#listen..ConfigStreamHandlerz Handler for a logging configuration request. It expects a completely new logging configuration and uses fileConfig to install it. c SsPz|j}|d}t|dkrtd|d}|j|}t||krb|||t|}q>|jjdurz|j|}|dur|d}z,ddl}| |}t |t sJt |WnDt yt|}z t|Wnt ytYn0Yn0|jjr|jjWn4tyJ}z|jtkr6WYd}~n d}~00dS)z Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work. z>LrNzutf-8) connectionrecvr3structunpackserververifydecodejsonloadsrrrrioStringIOr traceback print_excreadysetOSErrorerrno RESET_ERROR)rconnchunkZslenrrfilerrrrhandleGs8              z*listen..ConfigStreamHandler.handleN)rrrrrrrrrConfigStreamHandler@src@s0eZdZdZdZdedddfddZddZdS) z$listen..ConfigSocketReceiverzD A simple TCP socket-based logging config receiver. ra localhostNcSs>t|||f|td|_td|_||_||_dS)Nrra) rrr r abortrtimeoutrr)rhostportrrrrrrrusz-listen..ConfigSocketReceiver.__init__cSs`ddl}d}|sT||jggg|j\}}}|r<|t|j}tq | dS)Nr) selectsocketfilenorZhandle_requestr r rrZ server_close)rrrZrdwrexrrrserve_until_stoppeds  z8listen..ConfigSocketReceiver.serve_until_stopped)rrrrZallow_reuse_addressDEFAULT_LOGGING_CONFIG_PORTrrrrrrConfigSocketReceiverns  r cs&eZdZfddZddZZS)zlisten..Servercs4t|||_||_||_||_t|_dSr%) superrrcvrhdlrrr threadingEventr)rr r rr)Server __class__rrrs zlisten..Server.__init__cSsZ|j|j|j|j|jd}|jdkr0|jd|_|jt|a t | dS)N)rrrrrra) r rr rrZserver_addressrr r _listenerrr)rrrrrruns    zlisten..Server.run)rrrrr __classcell__rr)rrrsr)rrr Thread)rrrr rrrlisten,s.rcCs2tztrdt_daWtn t0dS)zN Stop the listening server which was created with a call to listen(). raN)r r rrrrrrr stopListenings r)NT)+rrrr Zlogging.handlersrrrr r socketserverrrrZ ECONNRESETrrrr$r)r rr^rr rIrqrvobjectrwrr{rbr|rr}rrrrrrrrrrsH  "&W! Az