Python module: Logging,

Source: Internet
Author: User
Tags add time truncated

Logging module:

Many programs have logging requirements, and the information contained in the log includes both normal program Access logs and possibly errors, warnings, and other information output. Python's logging module provides a standard log interface through which you can store logs in a variety of formats. Logging's logs can be divided into debug (), info (), warning (), error (), and Critical () 5 levels (in order, with higher levels).

The simplest usage:

Import logginglogging.warning ('User [Neo] attempted wrong password more than 3times'  ) logging.critical ('serveris down')#   Run Result:   # It's no different than print . #  WARNING:root:User [Neo] attempted wrong password more than 3times#< /c17>  CRITICAL:root:server is down

Log level:

Write the log in the file:

Importlogginglogging.basicconfig (filename='Logging_test.log', Level=logging.info)#Do basic configuration for the logging system. # level=logging. Info means: Only log is info or a log higher than info will be recorded in the file # log, only then the previous log will continue to record, will not overwrite the previous record. Logging.debug ('Debug Test') Logging.info ('Info Info') logging.warning ('warning!')#running Result: The Logging.info and logging.warning are recorded in the file "Logging_test.log" (suffix name of. log). # In this case the screen is not printed, that is, no output to the screen#is as follows:#INFO:root:INFO INFO#warning:root:warning!

Add time to the log:

Importlogginglogging.basicconfig (filename='Logging_with_time.log', level=logging.info, Format='% (asctime) s% (message) s', Datefmt='%y-%m-%d%h:%m:%s')#note the parameters inside ' format ' and ' Datefmt 'Logging.debug ('Debug Test') Logging.info ('Info Info') logging.warning ('warning!')#Run Result: info and above level are written in ' logging_with_time.log ' file#is as follows:#2018-02-09 11:37:11 Info Info#2018-02-09 11:37:11 warning!

In addition to adding time, you can customize other formats, and the following table is all supported formats:

Logging Advanced: Log output to screen and file simultaneously:

Python uses the logging module to log logs involving four main classes:

    • Logger provides an interface that the application can use directly
    • Handler send (logger created) log records to the appropriate destination output
    • Filter provides a fine-grained device to determine which log record to output
    • Formatter determining the final output format of the log record

The relationship between them is as follows:

Logger

Each program must first obtain a logger before outputting the information, such as:

ImportLogging#Generating Logger ObjectsLogger = Logging.getlogger ('Web')#logger usually corresponds to the module name of the program#set level levels for logger objects, such as set to info levelLogger.setlevel (Logging.info)#use Logger.setlevel () to set the level, logging, of the generated logger object. Info is set to the level specific to info, and if you don't set it, the system defaults to warning. # The effect of setting level on the Logger object: Logger. SetLevel () is equivalent to a global variable, The required output logs need to be generated by Logging.getlogger to generate the Logger object first, so before the logger object is generated, the output log level is detected to conform to the logger.setlevel level, and if it is compliant, the logger object is generated, and if non-conformance is ignored directly , the Logger object is not generated. Example: There are two logs that need to be output: Logger.debug (' Test Debug ') and Logger.info (' Test info '), when executing these two lines of code, as I have already set the level---for the build logger info:log Ger.setlevel (logging.info), debug level is below INFO, so Logger.debug (' Test Debug ') will not generate logger object, but Logger.info (' Test INFO ') The Logger object is generated (which is equivalent to filtering a portion of the data when the logger object is generated in the first step)

Handler

Handler is responsible for sending relevant information to the designated destination. The Python log system can be used in a variety of handler. You can output information to the console (screen), or you can export the information to a file and send the information to the network. You can also write your own handler.

Multiple handler can be attached to each logger. The common handler are as follows:

    1. Logging. Streamhandler # Use this handler to output information (output to the screen) to any file object similar to Sys.stdout or Sys.stderr
    2. Logging. Filehandler, like Streamhandler, is used to output log information to a file, but Filehandler will open the file for you (output to the file)
    3. There are two other uses: one is truncated according to the size of the file, and the other is truncated according to the time interval. Detailed reference: https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/logging-mo-kuai.html

Use the following:

#after generating the logger object, build the handler object, and then bind the handler to logger#Generating Handler ObjectsCH =logging. Streamhandler ()   #responsible for sending the handler (Sent to the screen, so the parentheses are empty)FI \logging. Filehandler ('Web.log')   #The suffix name for the handler # log file sent to file "Web.log":. Log#binds the generated handler object to the Logger objectLogger. AddHandler(CH)#Bind CH This handler object to loggerLogger. AddHandler(FH)#bind the FH handler object to the logger.#set the level of handlerCh.setlevel (Logging.info)#set the level of CH this handler object to infoFh.setlevel (logging. WARNING)#set the level of the FH handler object to Warning#about setting the level of the handler, it is similar to the level of logger, namely: if you do not set, the program will default level is warning, the level set by this step can again "filter" the data#what level does the level and handler set for the logger set, according to which level? The effect can be so understood: the required output of the log (such as: Logger.warning (XX)), the level of the logger set to "filter", and then in the generation of handler object this step, again through this step of the level "filter": Level of compliance,   The corresponding Handler;level is generated and the handler object is ignored and not generated. 

Formatter components:

The log's formatter is a standalone component that can be combined with handler to set the format of the message to send to the destination.

Usage:

#After you build the handler object, build the Formatter object, and then bind the formatter object and handler#Generating Formatter ObjectsCONSOLE_FMT = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (Lineno) d-% (message) s')#using the Logger name table aboveFILE_FMT = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s')#bind the formatter object to the handlerch. Setformatter(console_fmt) FH. Setformatter(FILE_FMT)

The following code together to see the results:

ImportLogging#Generating Logger ObjectsLogger = Logging.getlogger ('Web') Logger.setlevel (logging.info)#Generating Handler ObjectsCH =logging. Streamhandler () FH= Logging. Filehandler ('Web.log')#set levelCh.setlevel (logging. DEBUG) Fh.setlevel (logging. WARNING)#bind the handler to the logger.logger.addhandler (CH) logger.addhandler (FH)#Generating Formatter ObjectsCONSOLE_FMT = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (Lineno) d-% (message) s') file_fmt= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s')#% (name) s This name is the ' web ' in parentheses when generating logger#bind the formatter to the handlerCh.setformatter (CONSOLE_FMT) fh.setformatter (file_fmt) logger.debug ('Debug Test') Logger.info ('Info Test') logger.warning ('Warning Test') Logger.error ('Error Test') logger.critical ('Critical Test')#Log of output

Reference to filter usage: https://www.luffycity.com/python-book/di-4-zhang-python-ji-chu-2014-chang-yong-mo-kuai/logging-mo-kuai.html

Python module: Logging,

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.