python logging add features, mainly recording program running log, unified collection and analysis of

Transfer: https://www.cnblogs.com/jsondai/p/9663633.html

First, the log level

debug (debug information) info () warning (warnings) error (error message) critical (fatal information) from left to right is getting worse
Log level (level) description
DEBUG The most detailed log information, the typical scenario is a problem diagnosis
INFO Second only to the level of detail DEBUG, usually only record key node information to confirm everything is as we expected to work
WARNING Information when some undesirable things happen records (such as low disk space), but this time an application or normal operation
ERROR Because of a more serious problem leading to record certain functions can not work properly when the information
CRITICAL In the event of a serious error, leading to the recorded information can not continue to run the application
Note that the system only displays warning (warnings) above the level of logging, such as we enter the code below:
import logging
logging.debug ( 'This is a level debug information') # output is filtered out
logging.info ( 'This is a level information info') # output is filtered out
logging.warning ( 'This is a warning level information')
logging.error ( 'This is a level error information')
logging.critical ( 'This is a critical level information')

Console output

5 lines of code written data, the actual console only three lines, it is because the system default output warning (warning) and above the log.  

If you need to show all, you need to call

logging.basicConfig (level = logging.DEBUG) #basicConfig basic configuration can enter a keyword parameters, level is meant logging.DEBUG grade level must be capitalized if it is the calling function needs to lowercase

In the level where the display specified level. Plus run after logging.basicConfig, the following results can show all out

 

Second, the log output format

 The log output to the console or file

fp = logging.FileHandler ( 'a.txt', encoding = 'utf-8') # log records to a file
fs = logging.StreamHandler () # log to the console.

On the call handler 

Copy the code
import logging
LOG_FORMAT = "% (asctime) s -% (levelname) s -% (message) s" # formatted output log
DATE_FORMAT = "% m /% d /% Y% H:% M:% S% p" # Date Format
fp = logging.FileHandler('a.txt', encoding='utf-8')
fs = logging.StreamHandler()
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT, handlers=[fp, fs])    # 调用


logging.debug("This is a debug log.哈哈")
logging.info("This is a info log.")
logging.warning("This is a warning log.")
logging.error("This is a error log.")
logging.critical("This is a critical log.")
Copy the code

Console and log files to be able to show the

 

Guess you like

Origin www.cnblogs.com/fyly/p/11074847.html