Import logging
Logger = Logging.getlogger () #生成一个日志对象, () is the name of the log object, can not take, the name is not given is root
Handler=logging. Filehandler ("Log_test.txt") #生成一个handler (processor),
#formatter The following code to specify the output format of the log
FMT = '% (asctime) s-% (filename) s:% (lineno) s-% (name) s-% (message) s '
Formatter = logging. Formatter (FMT) # instantiation Formatter
Handler.setformatter (Formatter) # Add formatter for handler
Logger.addhandler (Handler)
Logger.setlevel (logging. NOTSET) #设置日志输出信息的级别
Logger.error ("This was an error message") #输出设置小于级别的将不会输出, so the settings here should be higher than setlevel
Logger.info ("This was an info message")
Logger.critical ("This is a critical message")
Python can generate a lot of handler, responsible for sending the log information created by logger to the specified destination, and the different handler types sent to different destinations. Filehandler writes the log information to the file, Streamhandler the log information to the console, Smtphandler sends the log information in the form of a message, and Sockethandler sends the log information to the TCP socket Datagramhandler send the log information with a UDP datagram
Format of the Formatter
| Property name |
Format |
Description |
| Name |
% (name) s |
The name of the log |
| Asctime |
% (Asctime) s |
Readable time, default format ' 2003-07-08 16:49:45,896 ', comma followed by milliseconds |
| FileName |
% (filename) s |
File name, part of pathname |
| Pathname |
% (pathname) s |
Full path name of the file |
| FuncName |
% (FuncName) s |
Call log multiple corresponding method name |
| LevelName |
% (LevelName) s |
Rank of log |
| Levelno |
% (Levelno) s |
Digitized log level |
| Lineno |
% (Lineno) d |
The number of rows recorded in the source code |
| Module |
% (module) s |
Module name |
| Msecs |
% (msecs) d |
The millisecond part of the time |
| Process |
% (process) d |
ID of the process |
| ProcessName |
% (ProcessName) s |
The name of the process |
| Thread |
% (thread) d |
The ID of the thread |
| ThreadName |
% (ThreadName) s |
The name of the thread |
| relativecreated |
% (relativecreated) d |
The relative time, in milliseconds, that the log was created |
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself
Python log output