py of the logging module

 

Reference: https://www.cnblogs.com/yuanchenqi/articles/5732581.html

A (simple application)

import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

Output:

WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message

Visible, default Python the logging module logs printed to the standard output, and only shows a greater than or equal WARNING level log, indicating that the default log level WARNING (log level Level CRITICAL> ERROR> WARNING> INFO> DEBUG > NOTSET), the default log format for the log level: Logger name: user output messages.

 

Two   flexible configuration log level and log format, output position

import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')

 See Output:
CAT /tmp/test.log 
Mon, On May 05, 2014 16:29:53 test_logging.py [Line:. 9] the DEBUG Debug Message
Mon, On May 05, 2014 16:29:53 test_logging.py [Line: 10] the INFO Message info
Mon, On May 05, 2014 16:29:53 test_logging.py [Line:. 11] Message warning the wARNING
Mon, On May 05, 2014 16:29:53 test_logging.py [Line: 12 is] Message error eRROR
Mon, 05 On May 16, 2014 : 29: 53 test_logging.py [line: 13] CRITICAL critical message

visible in logging.basicConfig () function can be changed by logging module specific parameters default behavior, the available parameters
filename: Creating FiledHandler (behind will use the specified file name explain in detail the concept of the handler), so logs are stored in the file specified.
filemode: File Open, this parameter is specified in the filename, the default value "a" may also be designated as "w".
format: log handler specified display format. 
datefmt: specify the date and time format. 
level: set the log level rootlogger (behind will explain specific concepts) of 
stream: Creating StreamHandler with the specified stream. Can specify the output to sys.stderr, sys.stdout or file (f = open ( 'test.log' , 'w')), default sys.stderr. If both lists the filename and stream two parameters, the stream parameter is ignored.

the format parameter string format may be used:
% (name) is the name of S Logger
% (levelno) s digital form log level
% (levelname) s log level text form
% (pathname) s call log output function module the full path name, it may not
% (filename) s calling module log output function filename
% (module) s calling module name log output function
% (funcName) s calling a function for a log output function of
% (lineno) d line of code calls log output function of the statement where
% (created) f the current time, represented by the floating-point standard UNIX time representation
% at (relativeCreated) d output log information, the number of milliseconds since Logger created
% (asctime) s current time string. The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma
% (thread) d thread ID. It may not have
% (threadName) s thread name. May not be
d Process ID% (process). May not
% (message) s user output message

Three logger objects

    These few examples, we learned logging.debug (), logging.info (), logging.warning (), logging.error (), logging.critical () (log information recorded respectively for different levels), logging .basicConfig () (to create a default stream processor (the StreamHandler) logging system is the default log format (Formatter), basic configuration settings (e.g., log levels, etc.) and added to a root logger (root Logger)) is several logging module level functions, in addition to a function block level is logging.getLogger ([name]) (returns a logger object will be returned if the root name is not specified logger)

     Look at a simple process:

the logging Import 

Logger logging.getLogger = () 
# Create a handler, a log file for writing 
FH = logging.FileHandler ( 'the test.log') 

# then create a handler, for output to the console 
ch = logging.StreamHandler ( ) 

Formatter logging.Formatter = ( '% (the asctime) S -% (name) S -% (levelname) S -% (Message) S') 

fh.setFormatter (Formatter) 
ch.setFormatter (Formatter) 

logger.addHandler (FH ) #logger plurality of objects can be added and fh ch objects 
logger.addHandler (ch) 

logger.debug ( 'Debug Message Logger') 
logger.info ( 'Message Logger info') 
logger.warning ( 'Message Logger warning') 
Logger. error ( 'error Message Logger') 
logger.critical ( 'Critical Message Logger')

Briefly explain, logging library provides a number of components: Logger, Handler, Filter, Formatter. Logger object provides an interface application can be used directly, Handler send logs to the appropriate destination, Filter provides a method of filtering log information, Formatter display format specified log.

     (1)

      Logger is a tree hierarchy, must obtain a Logger before outputting an information (If no acquisition is automatically created using the root Logger, as shown in the first example).
      logger = logging.getLogger () returns a default Logger i.e. root Logger, and applies a default log level, Handler and Formatter settings.
Of course, you can also specify a minimum log level by Logger.setLevel (lel), available log levels are logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL.
      Logger.debug (), Logger.info (), Logger.warning (), Logger.error (), Logger.critical () output different levels of logging, logging level is greater than or equal to only set the log level of the log will be export

logger.debug('logger debug message')  
logger.info('logger info message')  
logger.warning('logger warning message')  
logger.error('logger error message')  
logger.critical('logger critical message') 

Only output
2014-05-06 12 is: 54 is: 43,222 - the root - the WARNING - Message Logger warning
2014-05-06 12 is: 54 is: 43,223 - the root - ERROR - Message Logger error
2014-05-06 12 is: 54 is: 43,224 - root - CRITICAL - logger critical message
     from this output can be seen logger = logging.getLogger () returns Logger is root. There is no use logger.setLevel (logging.Debug) is displayed logger logging level is set so WARNIING default log level, so the output Results greater than or equal WARNIING level information.

     (2) If we create two logger objects: 

##################################################
logger1 = logging.getLogger('mylogger')
logger1.setLevel(logging.DEBUG)

logger2 = logging.getLogger('mylogger')
logger2.setLevel(logging.INFO)

logger1.addHandler(fh)
logger1.addHandler(ch)

logger2.addHandler(fh)
logger2.addHandler(ch)

logger1.debug('logger1 debug message')
logger1.info('logger1 info message')
logger1.warning('logger1 warning message')
logger1.error('logger1 error message')
logger1.critical('logger1 critical message')
  
logger2.debug('logger2 debug message')
logger2.info('logger2 info message')
logger2.warning('logger2 warning message')
logger2.error('logger2 error message')
logger2.critical('logger2 critical message')

There are two questions:

      <1> We obviously by logger1.setLevel (logging.DEBUG) the log level DEBUG logger1 order, why, when the display shows no DEBUG level log information, but from the beginning INFO level logs show it?

       Logger1 corresponding original and logger2 Logger instance is the same, as long as the logging.getLogger (name) Parameters name is returned Logger same example is the same, and only one, i.e. the Logger instance name correspondence. Mylogger disposed in logger2 example by logger2.setLevel (logging.INFO) logging level logging.INFO, so the output of the last log logger1 compliance level set later.

      <2> Why logger1, each corresponding output logger2 are displayed twice?
       That's because we pass logger = logging.getLogger () creates a root Logger display, and logger1 = logging.getLogger ( 'mylogger') creates a root Logger child (root.) mylogger, logger2 same. The children, grandchildren, great-grandchildren ...... not only sends a message distributed to his handler for processing will be passed to all the ancestors Logger process.

        ok, so now we have

# logger.addHandler(fh)

# Logger.addHandler (ch) commented, we will look at the effect of:

Because we annotated position logger objects displayed, so just use the default mode, that is, the standard output. Because its parent is not set files are displayed, so here printed only once.

Children, grandchildren, great-grandchildren ...... can inherit the log level layer by layer from the ancestors, Handler, Filter settings, you can also Logger.setLevel (lel), Logger.addHandler (hdlr), Logger.removeHandler (hdlr), Logger.addFilter (filt), Logger.removeFilter (filt). Set your own particular log level, Handler, Filter. Without setting inherited value is used.

<3> the Filter
     limit only meet the filter rule will log output.
     For example, we define a filter = logging.Filter ( 'abc') , and add to the Filter on a Handler, you can use the Logger Logger Handler's the only name with the prefix abc output their logs.

 

     filter = logging.Filter('mylogger') 

     logger.addFilter (filter)

     This is the only logger object screening

     If you want to screen all the objects, then:

      filter = logging.Filter('mylogger') 

      fh.addFilter (filter)

      ch.addFilter(filter)

      In this way, all additions or ch fh the logger objects will be screened.

 

Guess you like

Origin www.cnblogs.com/dbslinux/p/11204161.html