python logging

基础

Level When it’s used
DEBUG 展示信息细节,可用于问题的调试
INFO 确认程序按照预期在运行
WARNING (默认等级) 发生了意想不到的事情,或者在不久的将来出现了一些问题(例如“磁盘空间不足”)。 程序仍在按预期运行
ERROR 由于一个严重的问题,软件已经无法执行一些功能
CRITICAL 严重错误,程序本身可能无法继续运行

注意:确保每运行一次代码后,重启新的Python解释器;如果不同的代码沿用相同的解释器,会出现参数配置不正确、重复输出等问题。

简单输出

import logging
logging.warning('Watch out!')  # 会在控制台显示(默认级别)
logging.info('I told you so')  # 不会在控制台显示
WARNING:root:Watch out!

输出到文件

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

如果重复运行上面的代码,它会在之前生成的文档 example.log 中继续写入信息。若想每次运行的结果覆盖之前的结果,则需要:

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

改变输出信息格式

import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

显示时间

import logging
logging.basicConfig(format='%(asctime)s %(message)s') # 默认时间格式
logging.warning('is when this event was logged.')
2018-12-14 22:13:50,167 is when this event was logged.
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # 自定义时间格式
logging.warning('is when this event was logged.')
12/14/2018 10:14:12 PM is when this event was logged.

进阶

import logging

logger = logging.getLogger() # 创建 logger
logger.setLevel(level = logging.DEBUG) # 设置输出信息等级

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 定义输出格式

fh = logging.FileHandler('test.txt') # file handler 输出到文件
fh.setLevel(logging.WARNING) # 设置输出到文件的信息等级
fh.setFormatter(formatter) # 设置输出到文件的信息格式

ch = logging.StreamHandler() # console handler 输出到控制台界面
ch.setLevel(logging.DEBUG) # 设置输出到控制台界面的信息等级

logger.addHandler(fh) # 添加 fh 到 logger
logger.addHandler(ch) # 添加 ch 到 logger

logger.debug('000')
logger.info('111')
logger.warning('222')
logger.error('333')
logger.critical('444')

输出到控制台信息:

000
111
222
333
444

输出到文件 test.txt 信息:

2018-12-14 22:28:52,775 - root - WARNING - 222
2018-12-14 22:28:52,776 - root - ERROR - 333
2018-12-14 22:28:52,777 - root - CRITICAL - 444

更多信息查看官网:
https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial

你可能感兴趣的:(python)