Python logging记录日志
调试的几种方法:
- 使用
print()
在控制台上输出 - 使用
assert
断言 - 使用
logging
模块
logging提供了一组便利的函数,用来做简单的日志,(当然也能利用日志调试程序)。
与使用print()相比,logging有以下的优势:
- 你可以控制消息的级别,过滤掉那些并不重要的消息。
- 你可决定输出到什么地方,以及怎么输出。
logging跟踪事件的级别:
- DEBUG:详细信息,典型地调试问题时会感兴趣。
- INFO:证明事情按预期工作。
- WARNING:表明发生了一些意外,或者不久的将来会发生问题(如‘磁盘满了’)。软件还是在正常工作。
- ERROR:由于更严重的问题,软件已不能执行一些功能了。
- CRITICAL:严重错误,表明软件已不能继续运行了。
logging的默认级别为 WARNING,表示只有该级别及其以上的事件会被跟踪,当然也可以自定义跟踪的级别。
使用basicConfig()进行配置:
import logging
logging.basicConfig(level=logging.DEBUG)
for i in range(5):
x=i*i
logging.info('%d has been calculated',i)
输出为:
INFO:root:0 has been calculated
INFO:root:1 has been calculated
INFO:root:2 has been calculated
INFO:root:3 has been calculated
INFO:root:4 has been calculated
设置log文件和输出格式:
import logging
logging.basicConfig(filename="test.log",format="%(levelname)s:%(asctime)s %(message)s",level=logging.INFO)
for i in range(5):
x=i*i
logging.info('%d has been calculated',i)
输出为:
INFO:2017-08-15 16:17:58,448 0 has been calculated
INFO:2017-08-15 16:17:58,448 1 has been calculated
INFO:2017-08-15 16:17:58,448 2 has been calculated
INFO:2017-08-15 16:17:58,448 3 has been calculated
INFO:2017-08-15 16:17:58,448 4 has been calculated
每次运行的结果会追加到log文件中,如果你希望每次运新都重新开始,而不是记住先前运行的消息,你可以设置filemode参数:
logging.basicConfig(filename="test.log",filemode='w',format="%(levelname)s:%(asctime)s %(message)s",level=logging.INFO)
注意:对于basicConfig() 的调用要早于任何对debug()、info()等的调用。
通过INI文件进行配置
假设文件名为 logging_config.ini,加入内容:
[loggers]
keys=root
[handlers]
keys=stream_handler
[formatters]
keys=formatter
[logger_root]
level=DEBUG
handlers=stream_handler
[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)
[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
然后在源码中调用 logging.config.fileConfig() 方法:
import logging
from logging.config import fileConfig
fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
通过字典进行配置
你也可以使用字典实现详细配置:
import logging
from logging.config import dictConfig
logging_config = dict(
version = 1,
formatters = {
'f': {'format':
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
},
handlers = {
'h': {'class': 'logging.StreamHandler',
'formatter': 'f',
'level': logging.DEBUG}
},
root = {
'handlers': ['h'],
'level': logging.DEBUG,
},
)
dictConfig(logging_config)
logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
通过源码直接配置
import logging
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.debug('often makes a very good meal of %s', 'visiting tourists')
例如将logging同时输出到屏幕和文件
import logging
logger = logging.getLogger() # 不加名称设置root logger
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# 使用FileHandler输出到文件
fh = logging.FileHandler('log.txt')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
# 使用StreamHandler输出到屏幕
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
# 添加两个Handler
logger.addHandler(ch)
logger.addHandler(fh)
logger.info('this is info message')
logger.warn('this is warn message')
def get_logger(filename,level='info',mode='a',encoding='utf-8'):
level_relations = {
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'crit':logging.CRITICAL}
fmt='%(asctime)s-[%(pathname)s line:%(lineno)d]-%(levelname)s: %(message)s'
format_str = logging.Formatter(fmt)#设置日志格式
logger = logging.getLogger()
logger.setLevel(level_relations.get(level))#设置日志级别 (注意这里会创建一个标准输出的handler)
logger.handlers.pop()
sh = logging.StreamHandler()#往屏幕上输出
sh.setFormatter(format_str) #设置屏幕上显示的格式
fh = logging.FileHandler(filename=filename,mode='a',encoding='utf-8')
fh.setFormatter(format_str)
logger.addHandler(sh) #把对象加到logger里
logger.addHandler(fh)
return logger
logger = get_logger('log',level='debug')
更多内容见:
每个 Python 程序员都要知道的日志实践
python高级的日志教程
Advanced Logging Tutorial
日志Cookbook