Logging Module
functionality: Provides a standard logging interface through which you can store logs in a variety of formats.
Log 5 levels: Debug (), info (), warning (), error (), critical ()
logging.basicconfig function parameters:
FileName: Specify the log file name
FileMode: The same as the file function, specifies the open mode of the log file, ' W ' or ' A '
format: Specifies the formats and contents of the output, format can output a lot of useful information, as shown in the example above:
% (Levelno) s: Print log level numeric value
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the current executable, which is actually sys.argv[0]
% (filename) S: Print the current execution program name
% (FuncName) s: The current function of the print log
% (Lineno) d: The current line number of the print log
% (asctime) s: Time to print the log
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: Print process ID
% (message) s: Print log information
Datefmt: Specify the time format, same as Time.strftime ()
Level: Set the log levels, The default is logging. WARNING
Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously
Simple example: 5 log print and order
Import logging
Logging.debug (' Mess ')
Logging.info (' Mess ')
Logging.warning (' User warnning Log Info ')
Logging.error (' error ')
logging.critical (' Server is down ')
output critical log as follows:
CRITICAL:root:server is down
Example: Logging to a file
1 ImportLogging2 #open log file and set log write level to info above, set log file format, start with time, then log information3Logging.basicconfig (filename='Example.log',4Level=Logging.info,5format='% (asctime) s% (levelname) s% (message) s',6datefmt='%m%d%y%i:%m:%s%p')7Logging.info ('mess')8Logging.warning ('Warning')View Code
Logging module logging involves 4 classes:
1:logger provides an interface that the application can use directly
2:handler sends the log record (created by logger) to the appropriate destination output.
3:filter provides a fine-grained device to determine which log record to output
4:formatter determines the final output format of the log record.
Another: Logging there are 2 ways to cut logs (depending on the time or size)
Logger: Each program obtains a logger,logger that usually corresponds to the module name of the program before outputting the information. Such as:
LOG = Logging.getlogger (' Access.log ')
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 and 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 () is the log level that can be set.
Handler: Responsible for sending the information to the specified destination, such as: console, file, network or write your own handler. Add multiple handler by AddHandler ()
Handler.setlevel (LEL): Specifies the level of information being processed, which is ignored below the lel level.
Handler.setformatter (): Select a format for a Handler.
Handler.addfilter (filt), Handler.removefilter (filt): Add/Remove a Filter object.
The following are common handler:
1:logging. Streamhandler: is the screen output
2:logging. Filehandler: Output to File
3:logging.handlers.rotatingfilehandler: The file size can be managed, and when the specified size is reached, the current file is automatically renamed. Change to: file name. 1,.2,.3 so
Format: Rotatingfilehandler (Filename[,mode[,maxbytes[,backupcount]])
Parameters: MaxBytes is the file size, 0 is infinitely large. Backupcount: Number of backup files reserved.
4:logging.handlers.timerotatingfilehandler: Cut logs by Time
Format: Timerotatingfilehandler (Filename,[,when[,interval[,backupcount]])
Parameters: Interval time interval
When is a string, the unit of time interval has (s seconds, M minutes, H hours, D days, W weeks, midnight every morning)
Log Basic Flowchart
Example: implementation of the log screen and file output
1 ImportLogging2 #Custom log name Test-log3Logger = Logging.getlogger ('Test-log')4 #set minimum log level debug5 Logger.setlevel (logging. DEBUG)6 7 #add a handler to the screen output8CH =logging. Streamhandler ()9 #screen output Custom level is warningTen Ch.setlevel (logging. WARNING) One A #When you add a handler output to a file -FH = logging. Filehandler ('Access.log', encoding='Utf-8') - Fh.setlevel (logging. ERROR) the - #in defining the format of the log output (this definition is to file format) -Fh_formatter = logging. Formatter ('% (asctime) s% (process) d% (filename) s-% (levelname) s-% (message) s') - #This is defined as the screen printing format +Ch_formatter = logging. Formatter ('% (asctime) s,-% (name) s-% (levelname) s-% (message) s') - + #Next, associate the custom log format with the handler. A #Associate Files Handler at Fh.setformatter (fh_formatter) - #Associated Screen Handler - Ch.setformatter (ch_formatter) - - #Finally, the defined handler is associated to the logger, and the log is output through logger - Logger.addhandler (FH) in logger.addhandler (CH) - to #now, you can do the output log to test +Logger.debug ('Debug Message') -Logger.info ('Info Message') theLogger.warning ('warning Message') *Logger.error ('error Message') $Logger.critical ('Critical Message')View Code
Example: Cutting logs by file size or time
1 ImportLogging2 fromLoggingImporthandlers3Logger = Logging.getlogger (__name__)4Log_file ='Logname.log'5 #cut logs by file size6 #fh = handlers. Rotatingfilehandler (filename=log_file,maxbytes=10,backupcount=3,encoding= ' utf-8 ')7 #cut logs by file time, where ' s ' represents seconds8 #fh = handlers. Timedrotatingfilehandler (filename=log_file,when= "S", interval=5,backupcount=3,encoding= ' Utf-8 ')9 TenFormatter = logging. Formatter ('% (asctime) s% (module) s% (message) s') One Fh.setformatter (Formatter) ALogger.addhandler (FH)View Code
Python--Logging module