"Logging module of the Python log--understanding"

Source: Internet
Author: User

introduction
logging module is a python built-in standard module, mainly used for output log, you can set the level of output logs, log save path, log files and rollback, etc.
It can be said that the logging module consists mainly of 4 parts:
    *logger Logger , which provides interfaces that application code can use directly
    *handler processor , sends log records generated by the logger to the appropriate destination, or transmits the logger generated log to the specified location
     The *filters filter , which filters the output log, determines which logging to output
    *formatter Formatter , which controls the format of the log output, indicating the layout of the log records in the final output

1.1 Logger Recorder
before logging, you must first create a logger, which is to create an logger instance. If you do not create it explicitly, a root logger is created by default and the default log level, processor, and formatter are applied;
(The default log level is: WARN; default processor Handler[streamhandler, the log information will be printed out on the standard output]; The default formatter formatter[the default format is the format of the output in the first simple-to-use program])
Logger Creation Method:

1 logger = Logging.getlogger (logger_name)

"Attention" The loggers object has a parent-child relationship, and when there is no parent logger object its parent is root, and the parent-child relationship is corrected when it is owned. For example Logging.getlogger ("abc.xyz") creates two logger objects, one is the ABC parent object, one is the XYZ child object, and the ABC has no parent object so its parent is root. But in fact, ABC is a placeholder object (a virtual log object), and you can have no handler to process the log. But Root is not a placeholder object, and if a log object hits the log, its parent will receive the log at the same time, so some users find that a logger object is created with a log two times, because he created the logger to play the log, and the root object also plays the log

1.2 Handler processor
After you create the logger instance, you can use the following methods to set the log level to increase the processor handler

Logger.setlevel (logging. Error)  #  Set the log level to error, that is, only logs greater than or equal to error will be output

Log level:
notset--0
Debug--10
Info--20
Warning--30
Error--40
Critical--50
when a logger receives the log information, it first determines whether it meets the level, and if it decides to process it, passes the information to handler for processing.

Logger.addhandler (Handler_name)   #  Add a processor Logger.removehandler (handler_name)  for the Logger instance # removing a processor for a logger instance

A logger can have multiple handler, and each handler also has a log level, which means that logger can pass the logs to different handler depending on the log level. Of course, the same level can be passed to multiple handlers, which is flexibly set according to the requirements.
There are many kinds of handler processor types, more commonly used are three, Streamhandler,filehandler,nullhandler
Streamhandler:
To create a method:

SH = logging. Streamhandler (Stream=none)

After you create Streamhandler, you can set the log level by using the following methods, set the formatter formatter, and add or remove filter filters.

# Specify log level, logs below warn level will be ignored # set a formatter formattersh.addfilter (filter_name)  #  Add a filter that can add multiple #  Delete a filter 

Filehandler:
To Create a method :

FH = Logging.filehandler (filename, mode='a', Encoding=none,delay=false)

Nullhandler:
The Nullhandler class is located in the core logging package and does not do any formatting or output. Essentially it's a "do-nothing" handler, used by library developers

1.3 Filter Filters
Filters provides a finer-grained judgment to determine if the log needs to be printed. In principle handler obtaining a log is bound to be handled uniformly according to the level, but if Handler has a filter, the log can be processed and judged in extra terms. For example, filter can intercept or modify logs from a particular source, or even modify its log level (and then level judgment).
Both the logger and the handler can be installed with filter and can even be installed in series with multiple filter.
To create a method:

Filter = logging. Filter (name=")

1.4 Formatter Formatter
Formatter Specifies the format layout for the final print of a record. Formatter will stitch the information that is passed into a specific string. Use the formatter object to set the last rule, structure, and content of the log information, and the default time format is%y-%m-%d%h:%m:%s.
To create a method:

Formatter = logging. Formatter (Fmt=none, Datefmt=none)

where FMT is a formatted string of messages, Datefmt is a date string. If the FMT is not specified, the '% (message) s ' will be used. If you do not specify DATEFMT, the ISO8601 date format will be used.
In addition, logger is a tree-level structure, a logger can contain one or more handler and filter, a logger instance can add more handler, a handler can add more than one formatter or multiplefilter, and the log level will be inherited.

second, logging work flow
2.1 Logging module use process
* Import the logging module, the code in the logging module will be executed, this process will produce the logging log system default configuration
* Custom configuration, logging standard module supports three configuration methods: Dictconfig, Fileconfig, listen. Among them, Dictconfig is configured through a dictionary logger,handler,filterformatter;Fileconfig is configured through a dictionary, while listen listens on a network port and configures it by receiving network data. Of course, in addition to the above group configuration, you can also directly call Logger,handlerThe methods in the object are explicitly configured in the code.
* Use the GetLogger function in the global scope of the logging module to get a Logger object instance
* Log information is logged using methods such as debug,info,error,warn,critical in the Logger object.
2.2 Logging Module processing flow
* Determine if the level of the log is greater than the level of the Logger object, and if it is greater then execute down, otherwise the process ends
* Generate logs. The first step is to determine if there is an exception, and if so, add the exception information. The second step is to process the placeholder in the logging method, that is, the generic string format processing
* Filter using the filters registered in the Logger object. If there are multiple filters, then filter in turn. As long as a filter returns false, the filter is ended and the log information is discarded and no longer processed
, and the process is finished, otherwise the process is executed down.
* Find handler in the current logger object, and if no handler is found, look up to the Logger object's parent logger and, if one or more handler are located, use handler to process the log information in turn. However, in each handler process log information, the log information will first determine whether the level is greater than the level of handler, if greater than the execution (by the Logger object into the handler object), otherwise, the processing process ends.
* Executes the filter method in the Handler object, which executes the filter that is registered to the handler object in turn. If there is a filter to determine that the log information is false, then all the filter is no longer executed, and the log information is discarded directly, the processing process ends
* Format the final output using the formatter class. Note: Formatter with the 2nd step of the string format, it will add additional information, such as the time the log was generated, the source of the origin of the log sources of files, and so on.
* Really output log information (to network, file, terminal, mail, etc.). As to which destination to export, it is determined by the kind of handler.
Third, log configuration
3.1 How to configure
* Explicitly create logger logger, processor handler, and formatter formatter, and make related settings
* Configuration in a simple way, directly with the Basicconfig () function
* Configuration files are configured by using the Fileconfig () function to read the configuration file
* Configuration by Configuration dictionary, using the Dictconfig () function to read configuration information
* Configured over the network, using the Listen () function for network configuration
--basicconfig keyword parameters
FileName: Create a filehandle, using the specified file name, instead of using Streamhandle
FileMode: If the file name is indicated, indicates the mode of opening the files, the default is ' a '
Format:handler using the specified format string
detefmt: Using the specified time date format
level: Indicates the levels of root logger
stream: Initializes the Streamhandler with the specified stream. This parameter is not compatible with ' filename ', if two are available, ' stream ' is ignored
--format Format
% (Levelno) s--print log level values
% (levelname) s--print log level name
% (pathname) s--Prints the path of the currently executing program
% (filename) s--Prints the name of the currently executing program
% (funcName) s--the current function of the print log
% (Lineno) D--The current line number of the print log
% (asctime) s--time to print the log
% (thread) d--Print thread ID
% (threadname) s--Print thread name
% (process) D--Print process ID
% (message) s--Print process information

Content Source: Https://www.jianshu.com/p/feb86c06c4f4 http://python.jobbole.com/87300/

"Logging module of the Python log--understanding"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.