Below for you to share a python through the logging write log to file and console instances, has a good reference value, I hope to be helpful. Come and see it together.
As shown below:
Import Logging # Creates a logger logger = Logging.getlogger (' MyLogger ') logger.setlevel (logging. DEBUG) # Creates a handler that is used to write to the log file FH = logging. Filehandler (' Test.log ') fh.setlevel (logging. DEBUG) # Then create a handler for output to the console ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) # defines the output format of the handler formatter = logging. Formatter (' [% (asctime) s][% (thread) d][% (filename) s][line:% (Lineno) d][% (LevelName) s] # #% (message) s ') Fh.setformatter (Formatter) Ch.setformatter (formatter) # Add Logger handler (FH) Logger.addhandler to Logger.addhandler (ch # Record a log logger.info (' Foorbar ')
With regard to the configuration of formatter, the use of the form of% (<dict key>) s is the dictionary keyword substitution. The keywords provided include:
| Format |
Description |
| % (name) s |
Name of the Logger (logging channel). |
| % (Levelno) s |
Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL). |
| % (LevelName) s |
Text logging level for the message (' DEBUG ', ' INFO ', ' WARNING ', ' ERROR ', c27> ' CRITICAL '). |
| % (pathname) s |
Full pathname of the source file where the logging is issued (if available). |
| % (filename) s |
Filename portion of pathname. |
| % (module) s |
Module (name portion of filename). |
| % (FuncName) s |
Name of function containing the logging call. |
| % (Lineno) d |
Source line number where the logging is issued (if available). |
| % (created) f |
time when the LogRecord is created (as returned by Time.time ()). |
| % (relativecreated) d |
Time in milliseconds when the LogRecord is created, relative to the time of the logging module was loaded. |
| % (Asctime) s |
Human-readable time when the LogRecord is created. By default this is the form "2003-07-08 16:49:45,896" (the numbers after the comma was millisecond portion of the time) . |
| % (msecs) d |
Millisecond portion of the time when the LogRecord was created. |
| % (thread) d |
Thread ID (if available). |
| % (ThreadName) s |
Thread name (if available). |
| % (process) d |
Process ID (if available). |
| % (message) s |
The logged message, computed as msg % args. |