logging.config --- 日誌記錄配置¶
This section describes the API for configuring the logging module.
Configuration functions¶
The following functions configure the logging module. They are located in the
logging.config module. Their use is optional --- you can configure the
logging module using these functions or by making calls to the main API (defined
in logging itself) and defining handlers which are declared either in
logging or logging.handlers.
- logging.config.dictConfig(config)¶
Takes the logging configuration from a dictionary. The contents of this dictionary are described in Configuration dictionary schema below.
If an error is encountered during configuration, this function will raise a
ValueError,TypeError,AttributeErrororImportErrorwith a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error:A
levelwhich is not a string or which is a string not corresponding to an actual logging level.A
propagatevalue which is not a boolean.An id which does not have a corresponding destination.
A non-existent handler id found during an incremental call.
An invalid logger name.
Inability to resolve to an internal or external object.
Parsing is performed by the
DictConfiguratorclass, whose constructor is passed the dictionary used for configuration, and has aconfigure()method. Thelogging.configmodule has a callable attributedictConfigClasswhich is initially set toDictConfigurator. You can replace the value ofdictConfigClasswith a suitable implementation of your own.dictConfig()callsdictConfigClasspassing the specified dictionary, and then calls theconfigure()method on the returned object to put the configuration into effect:def dictConfig(config): dictConfigClass(config).configure()
For example, a subclass of
DictConfiguratorcould callDictConfigurator.__init__()in its own__init__(), then set up custom prefixes which would be usable in the subsequentconfigure()call.dictConfigClasswould be bound to this new subclass, and thendictConfig()could be called exactly as in the default, uncustomized state.在 3.2 版被加入.
- logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True, encoding=None)¶
Reads the logging configuration from a
configparser-format file. The format of the file should be as described in Configuration file format. This function can be called several times from an application, allowing an end user to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration).It will raise
FileNotFoundErrorif the file doesn't exist andRuntimeErrorif the file is invalid or empty.- 參數:
fname -- A filename, or a file-like object, or an instance derived from
RawConfigParser. If aRawConfigParser-derived instance is passed, it is used as is. Otherwise, aConfigParseris instantiated, and the configuration read by it from the object passed infname. If that has areadline()method, it is assumed to be a file-like object and read usingread_file(); otherwise, it is assumed to be a filename and passed toread().defaults -- Defaults to be passed to the
ConfigParsercan be specified in this argument.disable_existing_loggers -- If specified as
False, loggers which exist when this call is made are left enabled. The default isTruebecause this enables old behaviour in a backward-compatible way. This behaviour is to disable any existing non-root loggers unless they or their ancestors are explicitly named in the logging configuration.encoding -- The encoding used to open file when fname is filename.
在 3.4 版的變更: An instance of a subclass of
RawConfigParseris now accepted as a value forfname. This facilitates:Use of a configuration file where logging configuration is just part of the overall application configuration.
Use of a configuration read from a file, and then modified by the using application (e.g. based on command-line parameters or other aspects of the runtime environment) before being passed to
fileConfig.
在 3.10 版的變更: 新增了 encoding 參數。
在 3.12 版的變更: An exception will be thrown if the provided file doesn't exist or is invalid or empty.
- logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None)¶
Starts up a socket server on the specified port, and listens for new configurations. If no port is specified, the module's default
DEFAULT_LOGGING_CONFIG_PORTis used. Logging configurations will be sent as a file suitable for processing bydictConfig()orfileConfig(). Returns aThreadinstance on which you can callstart()to start the server, and which you canjoin()when appropriate. To stop the server, callstopListening().The
verifyargument, if specified, should be a callable which should verify whether bytes received across the socket are valid and should be processed. This could be done by encrypting and/or signing what is sent across the socket, such that theverifycallable can perform signature verification and/or decryption. Theverifycallable is called with a single argument - the bytes received across the socket - and should return the bytes to be processed, orNoneto indicate that the bytes should be discarded. The returned bytes could be the same as the passed in bytes (e.g. when only verification is done), or they could be completely different (perhaps if decryption were performed).To send a configuration to the socket, read in the configuration file and send it to the socket as a sequence of bytes preceded by a four-byte length string packed in binary using
struct.pack('>L', n).備註
Because portions of the configuration are passed through
eval(), use of this function may open its users to a security risk. While the function only binds to a socket onlocalhost, and so does not accept connections from remote machines, there are scenarios where untrusted code could be run under the account of the process which callslisten(). Specifically, if the process callinglisten()runs on a multi-user machine where users cannot trust each other, then a malicious user could arrange to run essentially arbitrary code in a victim user's process, simply by connecting to the victim'slisten()socket and sending a configuration which runs whatever code the attacker wants to have executed in the victim's process. This is especially easy to do if the default port is used, but not hard even if a different port is used. To avoid the risk of this happening, use theverifyargument tolisten()to prevent unrecognised configurations from being applied.在 3.4 版的變更: 新增
verify引數。備註
If you want to send configurations to the listener which don't disable existing loggers, you will need to use a JSON format for the configuration, which will use
dictConfig()for configuration. This method allows you to specifydisable_existing_loggersasFalsein the configuration you send.
Security considerations¶
The logging configuration functionality tries to offer convenience, and in part this is done by offering the ability to convert text in configuration files into Python objects used in logging configuration - for example, as described in User-defined objects. However, these same mechanisms (importing callables from user-defined modules and calling them with parameters from the configuration) could be used to invoke any code you like, and for this reason you should treat configuration files from untrusted sources with extreme caution and satisfy yourself that nothing bad can happen if you load them, before actually loading them.
Configuration dictionary schema¶
Describing a logging configuration requires listing the various
objects to create and the connections between them; for example, you
may create a handler named 'console' and then say that the logger
named 'startup' will send its messages to the 'console' handler.
These objects aren't limited to those provided by the logging
module because you might write your own formatter or handler class.
The parameters to these classes may also need to include external
objects such as sys.stderr. The syntax for describing these
objects and connections is defined in Object connections
below.
Dictionary Schema Details¶
The dictionary passed to dictConfig() must contain the following
keys:
version - to be set to an integer value representing the schema version. The only valid value at present is 1, but having this key allows the schema to evolve while still preserving backwards compatibility.
All other keys are optional, but if present they will be interpreted
as described below. In all cases below where a 'configuring dict' is
mentioned, it will be checked for the special '()' key to see if a
custom instantiation is required. If so, the mechanism described in
User-defined objects below is used to create an instance;
otherwise, the context is used to determine what to instantiate.
formatters - the corresponding value will be a dict in which each key is a formatter id and each value is a dict describing how to configure the corresponding
Formatterinstance.The configuring dict is searched for the following optional keys which correspond to the arguments passed to create a
Formatterobject:formatdatefmtstylevalidate(自 3.8 版起)defaults(自 3.12 版起)
An optional
classkey indicates the name of the formatter's class (as a dotted module and class name). The instantiation arguments are as forFormatter, thus this key is most useful for instantiating a customised subclass ofFormatter. For example, the alternative class might present exception tracebacks in an expanded or condensed format. If your formatter requires different or extra configuration keys, you should use User-defined objects.filters - the corresponding value will be a dict in which each key is a filter id and each value is a dict describing how to configure the corresponding Filter instance.
The configuring dict is searched for the key
name(defaulting to the empty string) and this is used to construct alogging.Filterinstance.handlers - the corresponding value will be a dict in which each key is a handler id and each value is a dict describing how to configure the corresponding Handler instance.
The configuring dict is searched for the following keys: