Python built-in module -logging

I. acquaintance logging module

#! / usr / bin / env Python 
# _ * _ Coding: UTF-8 _ * _ 
# @ author: yinzhengjie 
#blog: HTTP: //www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A 8C the A8% E5%%%% 96% 90% E8 E7 the BF%%% BB% E4% B9% B4 8B E8%%% the AF B7 / 
#email: [email protected] 

Import the logging 

logging.debug ( "Message Debug ") # alarm lowest level, detailed information only when diagnosing problems have interests. 

logging.info ( "info message") # alarm levels higher than debug, confirm that things proceed as expected. 

logging.warning ( "warning message") # alarm level is higher than the info, this mode is the default warning level! It indicates that some unexpected things happen, or some problems (such as "low disk space") in the near future. The software is still working properly. 

logging.error ( "error message") # warning alarm level than creams, as a more serious problem, the software also can not perform certain functions. 

logging.critical ( "critical message") # error even higher than the warning level, a critical error, indicating that the program itself may not continue to run. 





# Code executes the above results are as follows:  
the WARNING: the root: Message warning
ERROR:
CRITICAL:root:critical message

II. Log output file case

#! / usr / bin / env Python 
# _ * _ Coding: UTF-8 _ * _ 
# @ author: yinzhengjie 
#blog: HTTP: //www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A 8C the A8% E5%%%% 96% 90% E8 E7 the BF%%% BB% E4% B9% B4 8B E8%%% the AF B7 / 
#email: [email protected] 

Import the logging 

logging.basicConfig (particularly through # logging module parameters to change the default behavior; 
    level = logging.error, # set the alarm level to ERROR; 
    format = "% (asctime) S ---% (lineno) ---- S% (name) S:% ( message) s ", # custom print format; 
    filename =" yinzhengjie.txt ", # log file to the specified output; 
    the fileMode =" a ", is added in a manner # write log files, w is to cover the write way yo;



"" " 
Format parameter string format may be used: 
    .. 1>% (name) S 
         Logger name 
    . 2>% (levelno) s 
        digital form log level 
    . 3>% (levelname) s 
        text log level 
    4>.% (pathname) s 
        call to the full path name of the module log output function, may not be 
    5>.% (filename) s 
        calling module log output function filename 
    6>.% (module) s 
        call log output module name function 
    7>.% (funcName) s 
        call to the function name log output function 
    8>.% (lineno) d 
        line call log output function of the statement where 
    9>.% (created) f 
        the current time, with UNIX standard floating point numbers representing the time 
    10>. d% (relativeCreated) 
        when the output log information, since the number of milliseconds to create Logger 
    11>.% (asctime) s 
        string of the current time. the default format is "2003- 07-08 16:49:45,896. "Milliseconds after the comma
        % (thread) d thread ID. Maybe not
    13>.% (ThreadName) s 
        thread name. May not be 
    14>.% (Process) d 
        process ID. May not have 
    15>.% (Message) s 
        message is output to the user 
"" " 


logging.debug (" Debug the Message ") # Alarm lowest level, only when diagnosing problems have detailed information of interest. 

Logging.info (" the Message info ") # alarm levels higher than debug, confirm things as expected. 

logging.warning (" warning the Message ") # alarm level is higher than the info, this mode is the default alarm level! indicates that some unexpected things happen, or in the near future a number of issues (such as "low disk space"). the software is still working properly. 

logging.error ( "the Message error") # warning alarm level than creams, as a more serious problem, the software You can not perform certain functions. 

logging.critical ( "critical the Message") # error even higher than the warning level, a critical error, indicating that the program itself may not continue to run.

III. Log files, and simultaneous output to screen cases

#! / usr / bin / env Python 
# _ * _ Coding: UTF-8 _ * _ 
# @ author: yinzhengjie 
#blog: HTTP: //www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A 8C the A8% E5%%%% 96% 90% E8 E7 the BF%%% BB% E4% B9% B4 8B E8%%% the AF B7 / 
#email: [email protected] 

Import logging 

'' ' 
the Python use the logging module logging involves four main classes, using the official document summarizes the most appropriate: 
    . 1> .logger provides an interface application can be used directly; 
    2> .handler logging sent to the appropriate destination output (created Logger); 
    3> .filter provided fineness decide which device logging output; 
    . 4> .formatter determining the final output format of the log records. 
'' ' 

DEF get_logger (): 
    logger_obj logging.getLogger = () # create a logger object that provides an interface application can be used directly, the type of "<class' logging.RootLogger'>";
 
    FH = the logging. FileHandler ( "yinzhengjie.txt"
    fh.setLevel (logging.ERROR) # definition file output stream warning level; 

    CH = logging.StreamHandler () # create a screen output stream; 
    alarm level ch.setLevel (logging.CRITICAL) # define the screen output stream; 

    the Formater = logging.Formatter ( '% (asctime) s -% (name) s -% (levelname) s -% (message) s') # output from the log format definition, this format may be invoked screen output and file output stream stream ; 
    fh.setFormatter (the Formater) # add flower output format that we call format, as defined above, in other words, this handler to select a format; 
    ch.setFormatter (the Formater) 

    logger_obj.addHandler (FH) #logger objects can be created multiple file output stream (fh) and screen output stream (ch) yo 
    logger_obj.addHandler (ch) 

    return logger_obj # we will create a good logger object returned 


logger_obj = get_logger ()
 
logger_obj.info ( "info") 
logger_obj.error ( "error")
logger_obj.warning ( "warning") 
logger_obj.debug ( "Debug") 
logger_obj.critical ( "Critical") 



# screen output format is as follows: 
2018-03-08 00: 40: 20,716 - root - CRITICAL - Critical

Four .logging common Features

#! / usr / bin / env Python 
# _ * _ Coding: UTF-8 _ * _ 
# @ author: yinzhengjie 
#blog: HTTP: //www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A 8C the A8% E5%%%% 96% 90% E8 E7 the BF%%% BB% E4% B9% B4 8B E8%%% the AF B7 / 
#email: [email protected] 

'' ' 
the Python use the logging module logs involves four main classes, using the official document summarizes the most appropriate: 
    . 1> .logger provides an interface application can be used directly; 
    2> .handler the (Logger create) log sent to the appropriate destination output; 
    3> providing fineness .filter decide which device logging output; 
    . 4> .formatter determining the final output format of the log records. 
'' ' 


#Logger 
' '' 
    for each program must be obtained before a Logger output. Logger generally corresponds to the program module name. 
1>, such as chat GUI module can be obtained by its Logger:. 
The LOG = logging.getLogger ( "chat.gui") 
. 2> while the core module may be so: 
the LOG = the logging .getLogger ( "chat.kernel") 
3>. 
Logger.setLevel (LEL) 
4>. Add or delete the specified filter 
Logger.addFilter (FILT), Logger.removeFilter (FILT) 
5>. Add or remove the specified Handler 
Logger.addHandler (hdlr), Logger.removeHandler (hdlr) 
6> may be provided logging level 
logger.debug (), logger.info (), Logger.warning (), Logger.error (), Logger.critical () 
'' ' 


#handler 
' '' 
        Handler is responsible for sending the relevant target information to a specified destination. Python's logging system can use a variety of Handler. Some Handler can output information to the console, some Logger can be output to a file, and some Handler can send the information to the network. If that is not enough, you can also write your own Handler. AddHandler may be added by () method of a plurality of multi Handler 
#. 1>. Class designating information to be processed, below lel level information will be ignored 
Handler.setLevel (lel) 
# 2>. The handler to select a format 
Handler.setFormatter () 
# 3>. add or remove a filter objects
Handler.addFilter (filt), Handler.removeFilter (filt ) 
        Each Logger can attach multiple Handler. Next we introduce some common Handler: 
1> .logging.StreamHandler
3> .logging.handlers.RotatingFileHandler
        Handler can use this information to any output file object is similar to sys.stdout or sys.stderr of (file object). It is constructor: StreamHandler ([strm]), wherein the parameter is a file object strm. The default is sys.stderr 
2> .logging.FileHandler 
        and StreamHandler the like, for outputting information to a log file. But FileHandler will help you open the file. Its constructor is: FileHandler (filename [, mode] ), filename is the file name, you must specify a file name. mode is to open the way to a file. See the Python built-in function open () usage. The default is 'a', is added to the end of the file.
        The Handler similar to the above FileHandler, but it can manage file size. When the file reaches a certain size, it will automatically rename the current log file, and then create a new log file of the same name continues to be output. For example, the log file is chat.log. When chat.log reaches the size specified, RotatingFileHandler files automatically renamed chat.log.1. However, if chat.log.1 already exists, it will first chat.log.1 rename chat.log.2. . . Finally, re-create chat.log, it continues to output log information. It is constructor: RotatingFileHandler (filename [, mode [, maxBytes [, backupCount]]]), where filename and mode parameters and two FileHandler same. MaxBytes file is used to specify the maximum log file size. If maxBytes is zero, this means that log files can be infinite, then renaming process described above does not occur. backupCount for the specified number of backup files to keep. For example, if you specify 2, when the renaming process described above occurs, the original chat.log.2 will not be renamed, but was deleted.
4> .logging.handlers.TimedRotatingFileHandler
        The Handler and RotatingFileHandler similar, but it does not have to decide when to re-create the log file to determine the file size, but a certain time interval automatically create a new log file. Renaming process and RotatingFileHandler similar, but the new files are not figures, but the current time. It is constructor: TimedRotatingFileHandler (filename [, when [ , interval [, backupCount]]]), where filename BACKUPCOUNT parameters and parameters have the same meaning and RotatingFileHandler, interval is the time interval. when parameter is a string. Expressed in units of time intervals, a case-insensitive. It has the following values: (S [s], M [min], H [h], D [days], W [per week (interval == 0 behalf Monday)], midnight [morning day] 
'' '

V. automatically cut the number of cases and save the file in accordance with the specified time

#! / usr / bin / env Python 
# _ * _ Coding: UTF-8 _ * _ 
# @ author: yinzhengjie 
#blog: HTTP: //www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A 8C the A8% E5%%%% 96% 90% E8 E7 the BF%%% BB% E4% B9% B4 8B E8%%% the AF B7 / 
#email: [email protected] 

Import the logging 

from the logging Import handlers 

Logger the logging = .getLogger (__ name__) 

the log_file = "timelog.log" 

#fh handlers.RotatingFileHandler = (filename = the log_file, MaxBytes = 10, = BACKUPCOUNT. 3) 

FH = handlers.TimedRotatingFileHandler (= the log_file filename, When = "S",. 5 = interval The , backupCount = 3) #filename defined input information to the specified file, 
# When a specified unit is s (seconds), the frequency interval the time interval When the unit is designated yo (so you will be appreciated that frequency 5s) ; backupCount indicates the number of files backed up, I was assigned here three files. 

formatter = logging.Formatter ( '% (asctime ) s% (module) s:% (lineno) d% (message) s'

fh.setFormatter(formatter) #添加格式化输出
logger.addHandler(fh)

logger.warning("test1")
logger.warning("test2")
logger.warning("test3")
logger.warning("test4")

  

Guess you like

Origin www.cnblogs.com/wjcoding/p/11087950.html
Recommended