Python log output and python log
Import logging
Logger = logging. getLogger () # generate a log object, which is the name of the log object. It can be left blank. If the name is not specified, it is root.
Handler = logging. FileHandler ("Log_test.txt") # generate a handler (processor ),
# The code below formatter specifies the log output format
Fmt = '% (asctime) s-% (filename) s: % (lineno) s-% (name) s-% (message) s'
Formatter = logging. Formatter (fmt) # instantiate formatter
Handler. setFormatter (formatter) # Add formatter for handler
Logger. addHandler (handler)
Logger. setLevel (logging. NOTSET) # Set the log output level
Logger. error ("This is an error message") # If the output setting is smaller than the level, no output will be made. Therefore, the setting here should be higher than setLevel.
Logger.info ("This is an info message ")
Logger. critical ("This is a critical message ")
Python can generate many handler, which is responsible for sending the log information created by logger to the specified destination, and sending different Handler types to different destinations. FileHandler writes the log information to the file; StreamHandler outputs the log information to the console; SMTPHandler sends the log information in the form of an email; and SocketHandler sends the log information using TCP Socket; mongoramhandler sends log information using UDP datagram
Formatter format
| Attribute name |
Format |
Description |
| Name |
% (Name) s |
Log name |
| Asctime |
% (Asctime) s |
Readable time. The default format is '2017-07-08 16:49:45, 123456'. The value is millisecond after a comma. |
| Filename |
% (Filename) s |
File Name, part of pathname |
| Pathname |
% (Pathname) s |
File full path name |
| FuncName |
% (FuncName) s |
Method names corresponding to multiple call logs |
| Levelname |
% (Levelname) s |
Log Level |
| Levelno |
% (Levelno) s |
Digital Log Level |
| Lineno |
% (Lineno) d |
Number of lines in the source code of the recorded log |
| Module |
% (Module) s |
Module name |
| Msecs |
% (Msecs) d |
Millisecond in time |
| Process |
% (Process) d |
Process ID |
| ProcessName |
% (ProcessName) s |
Process name |
| Thread |
% (Thread) d |
Thread ID |
| ThreadName |
% (ThreadName) s |
Thread name |
| RelativeCreated |
% (RelativeCreated) d |
Relative time of log creation, in milliseconds |
The log level relationship is: CRITICAL> ERROR> WARNING> INFO> DEBUG> NOTSET. You can also define the log level by yourself.