python模块之logging
35、logging 模块
1、输出到单个文件test中。
import logging
logging.basicConfig(filename='test',level=logging.INFO,
format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug('nihao')
logging.critical('serious error')
2、输出到屏幕和多个文件。
import
logging
#create logger
logger
=
logging.getLogger(
'TEST-LOG'
)
logger.setLevel(logging.DEBUG) #==》表示日志级别最低就是debug。
# create console handler and set level to debug
ch
=
logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler and set level to warning
fh
=
logging.FileHandler(
"access.log"
)
fh.setLevel(logging.WARNING)
# create formatter
formatter
=
logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.debug(
'debug message'
)
logger.info(
'info message'
)
logger.warn(
'warn message'
)
logger.error(
'error message'
)
logger.critical(
'critical message'
)
3、日志记录格式:
![](https://images2015.cnblogs.com/blog/1002010/201608/1002010-20160817153849921-529411905.png)