Many programs have logging requirements, and the log contains information that has normal program access logs, there may be errors, warnings and other information output, Python's logging module provides a standard log interface, you can store various formats of the log, logging log can be divided into debug(),,, info() warning() and error() critical() 5个级别, below we look at how to use.
1 ImportLogging2Logging.debug ('Debug Message') 3Logging.info ('Info Message') 4Logging.warning ('warning Message') 5Logging.error ('error Message') 6Logging.critical ('Critical Message')
Output:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
Visible, by default Python's logging module prints the logs to standard output and only displays logs greater than or equal to warning level, indicating that the default logging level is set to warning ( log level level critical > ERROR > WARNING > INFO > DEBUG > NOTSET), the default log format is log level: Logger name: User output message.
Take a look at how these log levels stand for each other:
| 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. |
If you want to write the log into a file, it's also simple:
1 ImportLogging2 3Logging.basicconfig (filename='Example.log', level=logging.info)4Logging.debug ('This message should go to the log file')5Logging.info ('So should this')6Logging.warning ('and this, too')
One of the level=loggin in the following sentence. Info means that the logging level is set to info, that is, only logs that are higher than the log is info or the info level will be recorded in the file, in this case, the first log is not recorded, if you want to record the debug log, Change the log level to debug on the line.
1 logging.basicconfig (filename='example.log', Level=logging.info)
Feel the above log format forgot to add time, log do not know how to line, the following to add!
1 ImportLogging2Logging.basicconfig (format='% (asctime) s% (message) s', datefmt='%m/%d/%y%i:%m:%s%p')3Logging.warning ('is while this event was logged.')4 5 #Output612/12/2010 11:46:36 AM isWhen the This event is logged.
1 ImportLogging2Logging.basicconfig (level=logging. DEBUG,3format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s', 4datefmt='%a,%d%b%Y%h:%m:%s', 5Filename='/tmp/test.log', 6Filemode='W') 7 8Logging.debug ('Debug Message') 9Logging.info ('Info Message') TenLogging.warning ('warning Message') OneLogging.error ('error Message') ALogging.critical ('Critical Message')
To view the output:
Cat/tmp/test.log
Mon, 16:29:53 test_logging.py[line:9] Debug Debug message
Mon, 16:29:53 test_logging.py[line:10] Info Info message
Mon, 16:29:53 test_logging.py[line:11] WARNING WARNING message
Mon, 16:29:53 test_logging.py[line:12] Error error message
Mon, 16:29:53 test_logging.py[line:13] CRITICAL CRITICAL message
The Logging.basicconfig () function can be seen to change the default behavior of the logging module through specific parameters, with the parameters available
FileName: Creates a filedhandler with the specified file name (the concept of handler is explained in the back) so that the log is 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 the log levels for Rootlogger (which will explain the concepts behind)
Stream: Creates a streamhandler with the specified stream. You can specify the output to Sys.stderr,sys.stdout or the file (F=open (' Test.log ', ' W ')), and the default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored.
formatting strings that may be used in the format parameter:
% (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 |
If you want to print log in the screen and file log at the same time, you need to know a little bit more complex knowledge.
Python uses the logging module to log logs involving four main classes, which are best used in the official documentation:
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
1 ImportLogging2 3 #Create Logger4Logger = Logging.getlogger ('Test-log')5 Logger.setlevel (logging. DEBUG)6 7 8 #Create console handler and set level to debug9CH =logging. Streamhandler ()Ten Ch.setlevel (logging. DEBUG) One A #create file handler and set level to warning -FH = logging. Filehandler ("Access.log") - Fh.setlevel (logging. WARNING) the #Create Formatter -Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') - - #Add formatter to CH and FH + Ch.setformatter (Formatter) - Fh.setformatter (Formatter) + A #Add ch and fh to logger at logger.addhandler (CH) - Logger.addhandler (FH) - - #' Application ' code -Logger.debug ('Debug Message') -Logger.info ('Info Message') inLogger.warn ('warn message') -Logger.error ('error Message') toLogger.critical ('Critical Message')
Automatic file Truncation Example:
1 ImportLogging2 3 fromLoggingImporthandlers4 5Logger = Logging.getlogger (__name__)6 7Log_file ="Timelog.log"8 #fh = handlers. Rotatingfilehandler (filename=log_file,maxbytes=10,backupcount=3)9FH = handlers. Timedrotatingfilehandler (filename=log_file,when="S", interval=5,backupcount=3)Ten One AFormatter = logging. Formatter ('% (asctime) s% (module) s:% (Lineno) d% (message) s') - - Fh.setformatter (Formatter) the - Logger.addhandler (FH) - - +Logger.warning ("test1") -Logger.warning ("test12") +Logger.warning ("test13") ALogger.warning ("test14")
Python logging module