By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.
Print the log to the screen
1 Import Logging 2 3 logging.debug ('This isdebug message')4 logging.info (' This is info message')5 logging.warning ('this is Warning message')
View Code
Configure the output format and mode of log by Logging.basicconfig function
1 ImportLogging2 3Logging.basicconfig (level=logging. DEBUG,4format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s',5datefmt='%a,%d%b%Y%h:%m:%s',6Filename='Myapp.log',7Filemode='W')8 9Logging.debug ('This is debug message')TenLogging.info ('This is info message') OneLogging.warning ('This is warning message')View Code
Parameters of the Logging.basicconfig function:
FileName: Specify the log file name
FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '
Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:
% (Levelno) S: Print the value of the log level
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]
% (filename) s: Prints the current name of the executing program
% (funcName) s: Print the current function of the log
% (Lineno) d: Print the current line number of the log
% (asctime) s: Time to print logs
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: Print process ID
% (message) s: Print log information
DATEFMT: Specify time format, same as Time.strftime ()
Level: Sets the log levels by default to logging. WARNING
Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously
Output logs to files and screens at the same time
1 ImportLogging2 3Logging.basicconfig (level=logging. DEBUG,4format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s',5datefmt='%a,%d%b%Y%h:%m:%s',6Filename='Myapp.log',7Filemode='W')8 9 #################################################################################################Ten #define a Streamhandler, print info-level or higher log information to a standard error, and add it to the current log processing object # Oneconsole =logging. Streamhandler () A console.setlevel (logging.info) -Formatter = logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s') - Console.setformatter (Formatter) theLogging.getlogger ("'). AddHandler (console) - ################################################################################################# - -Logging.debug ('This is debug message') +Logging.info ('This is info message') -Logging.warning ('This is warning message')View Code
Python logging module