Log module
Python's logging module provides a standard log interface through which you can store logs in various formats, logging logs can be divided into debug (), info (), warning (), error () and critical () 5 levels.
The logs are also output to files and stdout.
ImportLogging#create logger object.Logger = Logging.getlogger ()#Create a Logger object to log logsLogger.setlevel (logging. DEBUG)#Create console handler and set level to debugConsole_handler = logging. Streamhandler ()#To create a console log objectConsole_handler.setlevel (logging. DEBUG)#Setting the console log level#create file handler and set level to warningFile_handler = logging. Filehandler ("Test.log", ' a ', encoding= ' UTF8 ')#Create a file log ObjectFile_handler.setlevel (logging. WARNING)#To create a file log object level#create log format.Formatter = logging. Formatter ('% (asctime) s | | % (filename) s | | [line:% (Lineno) d] | | % (levelname) s | | % (message) s')#Create a log formatFORMATTER.DATEFMT ='%a,%d%b%Y%h:%m:%s'#Add formatter to CH and File_handlerConsole_handler.setformatter (Formatter)#the same log level is called hereFile_handler.setformatter (Formatter)#Add ch and file_handler to loggerLogger.addhandler (Console_handler)#Logging Console LogsLogger.addhandler (File_handler)#Record file Log#call logger to generate a test logLogger.debug ('Debug Message') Logger.info ('Info Message') Logger.warn ('warn message') Logger.error ('error Message') logger.critical ('Critical Message')
Log level:
| Level When
it ' s used |
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things is working as expected. |
WARNING |
An indication this something unexpected happened, or indicative of some problem in the "near" (e.g. ' disk space low ') . The software is still working as expected. |
ERROR |
Due to a more serious problem, the software have not been able to perform some function. |
CRITICAL |
A serious error, indicating the program itself is unable to continue running. |
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 |
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
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 a specified handler
Logger.debug (), Logger.info (), logger.warning (), Logger.error (), logger.critical ():
Log levels that can be 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. You can add more than one handler by using 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
Common handler:
1) logging. Streamhandler
Its constructor is: Streamhandler ([STRM]).
Using this handler, you can output information to any file object, such as Sys.stdout or Sys.stderr. Where the STRM parameter is a file object. The default is Sys.stderr.
2) logging. Filehandler
Its constructor is: Filehandler (Filename[,mode]).
Similar to Streamhandler, used to output log information to a file. But Filehandler will open this file for you. 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
Its constructors are: Rotatingfilehandler (filename[, mode[, maxbytes[, Backupcount]]).
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.
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
Its constructor is: Timedrotatingfilehandler (filename [, when [, interval [, Backupcount]])
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.
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
Implement a log file every night rotate
ImportLogging fromLoggingImporthandlersImportTimelogger= Logging.getlogger (__name__,level=logging. DEBUG)
# logger name is __name__, is the name of the running program. # Logger.setlevel (logging. DEBUG)#Setting the log levelLog_filename ="test_rotate" #set the file name of the log#File_handler = handlers. Rotatingfilehandler (filename=log_file,maxbytes=10,backupcount=3) # Every 10bytes log file, keep up to 3 copies of log files#File_handler = handlers. Timedrotatingfilehandler (filename=log_file,when= "S", interval=5,backupcount=3) #每5秒一个日志文件, keep the latest 3 log filesFile_handler= Handlers. Timedrotatingfilehandler (filename=log_filename,when="S", interval=1,backupcount=3,encoding= ' Utf-8 ')#A log file is retained for three copies every 1 seconds. #file_handler.suffix = "%y-%m-%d_%h_%m_%s.log"#set the log file name suffix%y-%m-%d_%h_%m_%s.log#File_handler = handlers. Timedrotatingfilehandler (filename=log_file,when= "Midnight", Interval=1)#set to start a new file early in the morning#Formatter =logging. Formatter ("{' date ': '% (asctime) s ', ' filename ': '% (filename) s ', line ': '% (Lineno) d ', ' level ': '% (levelname) s ', ' message ': '% ( Message) s '}") File_handler.setformatter (formatter) Logger.addhandler (File_handler)#Generate log forIinchRange (13):#generate logs for 13 secondsLogger.debug ('Debug Message') Logger.info ('Info Message') Logger.warn ('warn message') Logger.error ('error Message') logger.critical ('Critical Message') Time.sleep (1) #每秒一次日志记录
Python logging module