logging-- log - reprinted 02

Reprinted: https://www.jianshu.com/p/e5595fd9f0e8

3, the process flow stream log

logging module logs the four components
Component Name The corresponding class name Functional Description
Logger Logger It provides an interface application may have been using
processor Handler The log records sent to the appropriate logger object created output
filter Filter Providing a more fine-grained control means to determine which of the output log, which log records discarded
Formatter Formatter The final output format depends on logging
The most common configuration is as follows:
method description
Logger.setLevel () Minimum level of severity set logger will be processed log messages
Logger.addHandler() And Logger.removeHandler () to add and remove objects for the logger object handler
Logger.addFilter () And Logger.removeFilter () add and remove a filter object for the logger objects
After the logger object configuration is complete, the following method may be used to create a log record:
method description
Logger.debug(), Logger.info(), Logger.warning(), Logger.error(), Logger.critical() Creating a logging level corresponds with their method names
Logger.exception() Create a similar Logger.error () log messages
Logger.log () You need to get a clear log level parameter to create a log record
Hierarchy and effective level description of the logger:
  • A name for the logger to be '.' Segmented hierarchical structure, each of '' the latter are logger '' in front of a logger Children, for example, there is a name for the foo logger, other names are foo.bar offspring foo.bar.baz and foo.bam all the foo.

  • logger has a concept of "effective level (effective level)" is. If that has not been explicitly set a level on the logger, then the logger is to use its parent's level; if its parent does not explicitly set level will continue to look up an effective level parent's parent, and so on, until you find one a clear set until the level of the ancestors. It should be noted, root logger always have a definite level setting (the default is WARNING). When deciding whether to handle an event that has occurred, the effective level logger will be used to decide whether to transfer the event to the handlers of the logger for processing.

  • Child loggers after completing the log messages, default messaging log handlers will give their ancestors loggers related. Therefore, all loggers are defined and configured handlers we do not have an application used, only need to configure handlers to a top-level logger, then follow the need to create a child loggers can be enough. We can also propagate by a logger's property to False to close this delivery mechanism.

Handler categories:

Handler is the role of the object (based on the level of log messages) will distribute the message to the handler specified location (file, web, mail, etc.). Logger object can add zero or more object handler itself by addHandler () method. For example, an application may want to implement the following log requirements:

1) all the logs are sent to a log file;

2) all the severity level greater than or equal to the transmission error log stdout (stdout);

3) all severity levels to send an email message to the address critical logs. This scenario requires three different handlers, each handler transmits a complex of particular severity to log a particular location.

Handler.setLevel (lel): Specifies the level of information to be processed, the information is below lel level will be ignored
Handler.setFormatter (): This handler to select a format
Handler.addFilter (filt), Handler.removeFilter (filt ): New add or delete a filter objects

Incidentally, the application code should not be directly instantiated and used Handler instance. Because Handler is a base class that defines only known handlers should be some interfaces, and provides default behavior of some subclasses can be used directly or coverage. Here are some common Handler:

Handler description
logging.StreamHandler Log messages to send output to a Stream, such as std.out, std.err or any file-like objects.
logging.FileHandler Send log messages to a disk file, the file size will grow indefinitely by default
logging.handlers.RotatingFileHandler Send log messages to a disk file, and supports the log file size by cutting
logging.hanlders.TimedRotatingFileHandler Send log messages to a disk file, and supports cutting the log files by time
logging.handlers.HTTPHandler Log messages to send a GET or POST HTTP server a way to
logging.handlers.SMTPHandler Log messages are sent to a designated email address
logging.NullHandler The example Handler ignores error messages, logging is usually want to use the library developers use to avoid 'No handlers could be found for logger XXX' appeared information.


 

Import the logging
 DEF log ():
     # Create logger, if the parameter is empty logger returns the root 
    logger = logging.getLogger ( " Nick " ) 
    Logger.setLevel (logging.DEBUG)   # Set logger log level 
# here judgment, if the logger .handlers list is empty, add, or go directly to write the log IF not logger.handlers:
         # create a Handler 
        FH = logging.FileHandler ( " test.log " , encoding = " UTF-8 " ) 
        CH = logging.StreamHandler ( ) # set the output log format
     
        
        = Formatter logging.Formatter ( 
            FMT = " % (the asctime) S% (name) S% (filename)% S (Message) S " , 
            datefmt = " % the Y /% m /%% X-D " 
            ) 
        # of handler format output 
        fh.setFormatter (Formatter) 
        ch.setFormatter (Formatter) 
        # of adding logger logs processor 
        logger.addHandler (FH) 
        logger.addHandler (CH) 
    return logger # returned directly logger 

logger = log () 
logger .warning ( " Muay Thai warning" ) 
Logger.info ( " Tip " ) 
logger.error ( " error " ) 
logger.debug ( " Troubleshooting " )

 

 

Automatically cut off according to time and save the file to specify the number of cases

 

Import the logging
 from the logging Import handlers 

Logger = logging.getLogger ( the __name__ ) 
the log_file = " timelog.log " 
# FH = handlers.RotatingFileHandler (= the log_file filename, MaxBytes = 10, = BACKUPCOUNT. 3) 
FH = handlers.TimedRotatingFileHandler (= the log_file filename, When = " S " , interval the =. 5, BACKUPCOUNT =. 3) # filename defined input information to the specified file, 
# When a specified unit is s (seconds), interval the frequency interval, the unit is When the designated yo ( so you can understand the frequency 5s); backupCount indicates the number of files backed up, I was assigned here three files. 
= logging.Formatter Formatter ( ' % (the asctime) S% (Module1) S:% (lineno) D% (Message) S' )   # Define the output format 
fh.setFormatter (Formatter) # add formatted output 
logger.addHandler (FH) 
logger.warning ( " test1 " ) 
logger.warning ( " test2 " ) 
logger.warning ( " Test3 " ) 
logger.warning ( " Test4 " )

 

Guess you like

Origin www.cnblogs.com/xiaobaibailongma/p/12417032.html