Overview:
Python's logging module provides a standard log interface through which you can store logs in a variety of formats, logging logs can be divided into,,, and debug()
info()
warning()
error()
critical() 5个级别。
Logging simple usage of log information
By default, the log level is higher than the info level to have content output.
Import Logginglogging.debug ("User[root] This is a {debug} message:") Logging.info ("User[root] This is a {info} message:") Logging.warning ("The server is down. This is a {warning} message: ") Logging.error ("The password is Error,con ' t to login. This is a {error} message: ") Logging.critical ("User[root] This is a critical message:") "" " WARNING:root:The server is down. This is a {warning} message: ERROR:root:the password is Error,con ' t to login. This is a {error} message: Critical:root:user[root] This is a CRITICAL message: "" "
Logging 5 log levels represent the meaning:
Writes logging log information to a file
Logging.basicconfig function to the output format and configuration of the log, level settings log output levels, Farmat set the format of the journal Save, DATEFMT set the format of the log time, the filename log to save the name of the file, FileMode file Input mode: "A" is appended.
Import Logginglogging.basicconfig (level=logging.info, format= '% (asctime) s% (filename) s[line:% (lineno) d]% ( LevelName) s% (message) s ', datefmt= '%a,%d%b%Y%h:%m:%s ', filename= "MyLOG.log", filemode= "a") Logging.debug (' This message should go to the log file ') Logging.info ("So should this,info log") logging.warning (' This is war Ning message ')
MyLOG.log The log information in the document:
Thu, 15:59:10 log_v1.py[line:55] INFO so should this,info Logthu, + 15:59:10 log_v1.py[line:56] WARN ING This is warning Messagethu, 15:59:57 log_v1.py[line:55] INFO so should This,info Logthu, 2017 15:59 : log_v1.py[line:56] WARNING This is WARNING message
Logging Log Format:
% (name) s |
Logger's name. |
% (Levelno) s |
Log level in digital form |
% (LevelName) s |
Log level in text form |
% (pathname) s |
The full path name of the module that called the log output function may not have |
% (filename) s |
The file name of the module that called the log output function |
% (module) s |
Call the module name of the log output function |
% (FuncName) s |
Function name of the call log output function |
% (Lineno) d |
The line of code where the statement that called the log output function is located |
% (created) f |
Current time, represented by the UNIX standard floating-point number representing the time |
% (relativecreated) d |
The number of milliseconds since logger was created when the log information is output |
% (Asctime) s |
The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds |
% (thread) d |
The thread ID. Probably not. |
% (ThreadName) s |
The name of the thread. Probably not. |
% (process) d |
The process ID. Probably not. |
% (message) s |
User-Output messages |
Output logging logs to screen and file
Python uses the logging module to log logs involving four main classes:
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 interface:
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 1:
Import Logginglogging.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= "Myapp.log", filemode= "a") #输出到文档console = logging. Streamhandler () # defines a streamhandler that prints info-level or higher log information to a standard error and adds it to the current log-processing object Console.setlevel (Logging.info) Formatter = logging. Formatter ('% (asctime) s-% (name) -12s:% (levelname) -8s% (message) s ') # screen Output console.setformatter (Formatter) Logging.getlogger (""). AddHandler (console) Logging.debug (' This is the Debug message ') Logging.info (' This is Info message ') Logging.warning (' This is warning message ')
# example 2 (another classic notation):
Import Logginglogger = Logging.getlogger ("logger") logger.setlevel (logging. DEBUG) ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) fh = logging. Filehandler ("MyLog.log") fh.setlevel (logging. DEBUG) formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') Ch.setformatter (Formatter) fh.setformatter (Formatter ) Logger.addhandler (CH) logger.addhandler (FH) # Log information Logger.debug (' This is the Debug message ') Logger.info (' This is info Message ') Logger.warn (' This was warning message ') logger.error (' This is the error message ') logger.critical (' This is critical Message ')
Log information for the screen output:
2017-08-17 16:39:55,971-logger-debug-this is DEBUG message2017-08-17 16:39:55,971-logger-info-this is INFO mes SAGE2017-08-17 16:39:55,971-logger-warning-this is WARNING message2017-08-17 16:39:55,971-logger-error-this is Error MESSAGE2017-08-17 16:39:55,971-logger-critical-this is CRITICAL message
Log information in the MyLog.log file:
2017-08-17 16:41:49,346-logger-debug-this is DEBUG message2017-08-17 16:41:49,346-logger-info-this is INFO mes SAGE2017-08-17 16:41:49,346-logger-warning-this is WARNING message2017-08-17 16:41:49,346-logger-error-this is Error MESSAGE2017-08-17 16:41:49,346-logger-critical-this is CRITICAL message
Configure logger by configuration file:
To define a configuration file logger.conf
#logger. Conf###############################################[loggers]keys=root,example01,example02[logger_root] Level=debughandlers=hand01,hand02[logger_example01]handlers=hand01,hand02qualname=example01propagate=0[logger_ example02]handlers=hand01,hand03qualname=example02propagate=0###############################################[ Handlers]keys=hand01,hand02,hand03[handler_hand01]class=streamhandlerlevel=infoformatter=form02args= ( Sys.stderr,) [Handler_hand02]class=filehandlerlevel=debugformatter=form01args= (' Myapp.log ', ' a ') [HANDLER_HAND03] Class=handlers. rotatingfilehandlerlevel=infoformatter=form02args= (' Myapp.log ', ' a ', 10*1024*1024, 5) ############################ ###################[formatters]keys=form01,form02[formatter_form01]format=% (asctime) s% (filename) s[line:% ( Lineno) d]% (levelname) s% (message) sdatefmt=%a,%d%b%Y%h:%m:%s[formatter_form02]format=% (name) -12s:% (levelname) -8s % (message) sdatefmt=
To obtain a log of the Logging.config configuration:
Import Loggingimport logging.configlogging.config.fileConfig ("logger.conf") logger = Logging.getlogger ("example01") Logger.debug ("This is the Debug message") Logger.info (' This is Info message ') logger.warning (' It is warning message ')
Log output results:
EXAMPLE01 : Info This is info messageexample01 : WARNING This is WARNING message
Reference link 1:http://www.cnblogs.com/tkqasn/p/6020282.html
Reference link 2:http://www.cnblogs.com/alex3714/articles/5161349.html
Python logging module