Python Common Module--logger module

Source: Internet
Author: User

Python's logging module provides a common logging system, and skilled use of the logging module makes it easy for developers to develop third-party modules or their own Python applications.

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

Logger: Provides an interface that the application can use directly;

Handler: Sends (logger created) log records to the appropriate destination.

Filter: Provides an elegant way to determine whether a log record is sent to handler.

Formatter: Specifies the specific format of the logging output. The formatter method requires two parameters: the format string of the message and the date string, both of which are optional.

Logging.getlogger ([name]): Returns a Logger object that returns root logger if no name is specified.

Logging.basicconfig (): Establishes a streamhandler for the logging system with the default formatter, sets the base configuration and adds it to root logger

There are 5 modes in log printing:

Logging.debug (): Debug mode, not must appear, but if there is a problem need to use its information.

Logging.info (): Information mode, which must appear but has no effect on the normal operation of the program.

Logging.warning (): Warning mode does not cause program errors, but may print when problems occur.

Logging.erroe (): Error mode, program error.

Loggingcirtical (): Critical mode, the program crashes.

Each program obtains a Logger,logger before outputting the information that usually corresponds to the module name of the program.

LOG = Logging.getlogger ("Chat.gui")

And the core module can do this:

LOG = Logging.getlogger ("Chat.kernel")

Logger.setlevel (LEL): Specifies the lowest log level, and the level below LEL will be ignored. Debug is the lowest built-in level and critical is the highest.

Logger.addfilter (filt), Logger.removefilter (filt): Adds or removes the specified filter.

Logger.addhandler (HDR), Logger.removehandler (HDR): Adds or deletes the specified handler

Operating levels for different modes:

Import logging>>> logging. NOTSET0>>> logging. DEBUG10>>> logging.info20>>> logging. WARNING30>>> logging. ERROR40>>> logging. CRITICAL50

NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL

If the level of Looger is set to info, the logs less than the info level are not output, and logs greater than or equal to the info level are output.

The handler object is responsible for sending relevant information to the specified destination. Python's log system can be used in a variety of handler. Some handler can output information to the console, some logger can output information to a file, some handler can send information to the Internet, if not enough, you can also write their own handler can be AddHandler () Ways to add multiple handler

Handler.setlevel (LEL): Specifies the level of information being processed, and information below the LEL level is ignored.

Handler.setformatter (): Choose a format for this Handler

Handler.addfilter (filt), Handler.removefilter: Adds or deletes a filter object.

Each logger can be attached to multiple handler, the following are several common:

(1) logging. Streamhander: Screen Stream object

(2) logging. Filehandler: Used to output log information to a file

Formatters

Formatter the default time format for setting the last rule, structure, and content of the log information is%y-%m-%d%h:%m:%s

 import   Logginglog  = Logging.getlogger () #   Get an instance  sh = logging. Streamhandler () #   get a screen-flow send station  log.addhandler (SH)  #   The console is associated to the instance  log.warning (  " logger warning message   ") #   Invoke instance consent information  Log.error ( " logger error message   " )  #   No formatting, only the most original output to the screen  

Results:

Logger warning message   #输出到屏幕logger error message

Only the following output to the file:

ImportLogginglog=logging.getlogger ()#get an instanceConsole= Logging. Filehandler ('Test.log') #控制台formatter= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') Log.addhandler (console) Console.setformatter (formatter) #绑定格式LOG. Warning ('Logger warning message') Log.error ('Logger error message')

Results:

2017-11-23 20:46:49,396-root-warning- logger WARNING message2017-11-23 20:46:49,396-root-error-logger Error message

Comprehensive Example:

ImportLogginglogger=Logging.getlogger () #实例化一个logger对象#create a handler to write to the log fileFH = logging. Filehandler ('Test.log') #将相关信息发送到目的地#create another handler for output to the consoleCH =logging. Streamhandler ()
#指定文件, you can not specify formatter= Logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') Fh.setformatter (formatter)#file handle binding format,Ch.setformatter (Formatter) logger.setlevel (logging.info) Set the file level, default Vwarninglogger.addhandler (FH)#Logger object can add multiple FH and CH objects (logger bind file handle)logger.addhandler (CH) logger.debug ('Logger Debug Message')#OutputLogger.info ('Logger Info Message') logger.warning ('Logger warning message') Logger.error ('Logger error message') logger.critical ('Logger Critical Message')

Python Common Module--logger module

Related Article

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.