Many programs have logging requirements, and the log contains information that has normal program access logs and may have errors, warnings and other information output, Python's logging module provides a standard log interface through which you can store logs in various formats, log level level: critical > Error > Warning > Info > Debug
See what each log level means:
Simply tell the log to print to the screen:
1>>>ImportLogging2>>> Logging.debug ('Test Debug')3>>> Logging.info ('Test Info')4>>> logging.warning ('Test Warning')5 WARNING:root:test WARNING6>>> Logging.error ('Test Error')7 ERROR:root:test ERROR8>>> logging.critical ('Test Critical')9 CRITICAL:root:test CRITICALTen>>>
By default, only logs that are greater than or equal to the warning level are displayed.
Flexible configuration log level, log format, output location:
1 ImportLogging2Logging.basicconfig (filename='App.log', level=logging. debug,format='% (asctime) s% (filename) s[line:% (lineno) d]% (message) s', datefmt='%y-%m-%d')3Logging.info ('Test Info')4Logging.debug ('Test Debug')5Logging.warning ('Test Warning')6Logging.error ('Test Error')7Logging.critical ('Test Critical')
To view the output:
2017-07-17 logging module. py[line:7] Test Info
2017-07-17 logging module. py[line:8] Test Debug
2017-07-17 logging module. py[line:9] Test Warning
2017-07-17 logging module. py[line:10] Test Error
2017-07-17 logging module. py[line:11] Test Critical
In the Logging.basicconfig () function, you can change the default behavior of the logging module through specific parameters, the available parameters are filename: Create a filedhandler with the specified file name (the concept of handler is explained in the back), This allows the log to be stored in the specified file.FileMode: File is opened by using this parameter when filename is specified, and the default value is "a" and can be specified as "W". Format : Specifies the log display format used by handler. datefmt: Specifies the date time format. level: Set Rootlogger (The following explains the specific concept) stream: Create Streamhandler with the specified stream. You can specify the output to Sys.stderr,sys.stdout or to a file, and the default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored.
Formatted string that may be used in the format parameter:% (name) s logger name% (Levelno) s number form log level% (levelname) s text form log level% (pathname) s The full pathname of the module that calls the log output function, The file name of the module that may not have% (filename) s call log output function% (module) s call log output function module name% (funcName) s call log output function name% (Lineno) d Call Log output function The statement that is located in the line% ( Created) F current time, the current time in the number of milliseconds (asctime) s string as a percentage of the time that the UNIX standard represents a floating-point (relativecreated) d output log information, since logger was created. The default format is "2003-07-08 16:49:45,896". The comma is followed by the millisecond% (thread) d thread ID. There may not be a% (threadname) s thread name. There may not be a% (process) d process ID. Messages that may not have a% (message) s user output
To make more flexible control of logging, you must understand the concept of Logger,handler,formatter,filter:
Logger provides an interface that the application can use directly;
Handler sends the log record (created by logger) to the appropriate destination output;
Filter provides a fine-grained device to determine which log record to output;
Formatter determines the final output format of the log record.
Logger
Each program obtains a logger before outputting the information. Logger usually corresponds to the program's module name, such as the chat tool's graphical interface module can get its logger:
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 is ignored. Debug is the lowest built-in level, critical is the highest
Logger.addfilter (filt), Logger.removefilter (filt): Add or remove the specified filter
Logger.addhandler (HDLR), Logger.removehandler (HDLR): Add or remove the specified handler
Logger.debug (), Logger.info (), logger.warning (), Logger.error (), logger.critical (): Log levels you can set
Handler
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 the information to a file, and some handler can send information to the network. If you feel that it is not enough, you can write your own handler. Multiple handler can be added through the AddHandler () method
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 (filt): Add or remove a filter object
Multiple handler can be attached to each logger. Next, let's introduce some common handler:
1) logging. Streamhandler
Using this handler, you can output information to any file object, such as Sys.stdout or Sys.stderr. Its constructor is:
Streamhandler ([STRM])
Where the STRM parameter is a file object. Default is Sys.stderr
2) logging. Filehandler
Similar to Streamhandler, used to output log information to a file. But Filehandler will open this file for you. Its constructor is:
Filehandler (Filename[,mode])
FileName is a file name and you must specify a file name.
Mode is how the file is opened. See the use of the Python built-in function open (). The default is ' a ', which is added to the end of the file.
3) Logging.handlers.RotatingFileHandler
This handler is similar to the filehandler above, but it can manage the file size. When the file reaches a certain size, it automatically renames the current log file and then creates a new log file with the same name to continue the output. For example, the log file is Chat.log. When the chat.log reaches the specified size, Rotatingfilehandler automatically renames the file to Chat.log.1. However, if chat.log.1 already exists, it will first rename chat.log.1 to chat.log.2 ... Finally, re-create the Chat.log and continue to output the log information. Its constructor is:
Rotatingfilehandler (filename[, mode[, maxbytes[, Backupcount]])
where filename and mode two parameters are the same as Filehandler. The
MaxBytes is used to specify the maximum file size for the log file. If MaxBytes is 0, it means that the log file can be infinitely large, and the renaming process described above does not occur. The
Backupcount is used to specify the number of reserved backup files. For example, if you specify 2, when the renaming process described above occurs, the original chat.log.2 is not renamed, but is deleted.
4) Logging.handlers.TimedRotatingFileHandler
This handler is similar to Rotatingfilehandler, however, it does not determine when to recreate the log file by judging the size of the file, but instead automatically creates a new log file at a certain time interval. The process of renaming is similar to Rotatingfilehandler, but the new file is not an appended number but the current time. Its constructor is:
Timedrotatingfilehandler (filename [, when [, interval [, Backupcount]])
where the filename parameter and the Backupcount parameter and the Rotatingfilehandler have the same meaning.
Interval is the time interval.
The When parameter is a string. A unit that represents a time interval, not case-sensitive. It has the following values:
s S
M min
H hours
D Day
W per week (Interval==0 on behalf of Monday)
Midnight every morning
Example of screen output and file output:
1 ImportLogging2Logger = Logging.getlogger ()#define the corresponding program module name name, default is root3 #Logger.setlevel (logging. DEBUG) #指定最低的日志级别4ch = logging. Streamhandler ()#Log output to screen console5Ch.setlevel (logging. WARNING)#set the log level6 7FH = logging. Filehandler ('Access.log')#output log information to a file Access.log8Fh.setlevel (Logging.info)#set output to file minimum log level9 Ten #Create Formatter OneFormatter = logging. Formatter ('% (asctime) s (name) s% (levelname) s-% (message) s')#defining the log Output format A - #Add formatter to CH and FH -Ch.setformatter (Formatter)#Select a format the Fh.setformatter (Formatter) - -Logger.addhandler (CH)#adds the specified handler - Logger.addhandler (FH) + #' Application ' code -Logger.debug ('Debug Message') +Logger.info ('Info Message') ALogger.warn ('warn message') atLogger.error ('error Message') -Logger.critical ('Critical Message')
Python3 Logging Module