logging log module _python

A, logging module

1, function

Python logging module is built standard modules, mainly for outputting the operation log, the log output level can be set, save the log path, the log file rollback like; Print compared, has the following advantages:

  • You can set different log levels, output in the release version only important information without having to show a lot of debugging information;

  • All print information is output to the standard output, seriously affecting other developers view data from the standard output; logging can be determined by the developers to output information to where, and how output.

2, log level and modify the default level

The most detailed log information DEBUG, typical application scenarios are diagnosing problems

INFO level of detail behind DEBUG, usually only record key node information to confirm everything is as we expected to work

WARNING information when certain undesirable things happen records (such as low disk space), but this time an application or normal operation

ERROR Due to a more serious problem caused some of the information recording function does not operate properly

CRITICAL When serious errors occur, leading to the recorded information can not continue to run the application

The default logging level: WARNING

Modify the default level: basicConfig

logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt = '%Y-%m-%d %H:%M:%S %a'
)    #修改日志级别为debug
logging.debug("msg1")    #2020-01-06 23:12:04 Mon root DEBUG msg1
logging.info("msg2")   #2020-01-06 23:12:04 Mon root INFO msg2
logging.warning("msg3")   #2020-01-06 23:12:04 Mon root WARNING msg3
logging.error("msg4")   #2020-01-06 23:12:04 Mon root ERROR msg4
logging.critical("msg5")   #2020-01-06 23:12:04 Mon root CRITICAL msg5

basicConfig () method arguments detailed:

 

 3, the log output

Simple to use:

import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt = '%Y-%m-%d %H:%M:%S %a'
) #修改日志级别为debug,设置打印格式内容
logging.debug("msg1") #2020-01-06 23:12:04 Mon root DEBUG msg1
logging.info("msg2") #2020-01-06 23:12:04 Mon root INFO msg2
logging.warning("msg3") #2020-01-06 23:12:04 Mon root WARNING msg3
logging.error("msg4") #2020-01-06 23:12:04 Mon root ERROR msg4
logging.critical("msg5") #2020-01-06 23:12:04 Mon root CRITICAL msg5

2, log stream processing mode

import logging
logger=logging.getLogger()
#创建handler,用于输出到日志文件
fh=logging.FileHandler('test.log')
#创建handler,用于输出到控制台
ch=logging.StreamHandler()
#设置一种打印格式
formatter=logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
#运用对应的格式
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#应用对应的handler
logger.addHandler(fh)
logger.addHandler(ch)
logger.warning('lsss') #2020-01-06 23:32:44,185 root WARNING lsss

Guess you like

Origin www.cnblogs.com/chenxiaozan/p/12159143.html