日志记录
边学习边记录,参照logging官方文档,时间宝贵,开始正题:
以下为logging级别,按照严重程度递增排序:
DEBUG:详细信息,通常在调试时候才有意义
INFO:确保事情如期进行
WARNING:警告性错误,可能出现问题,但不影响程序运行。
ERROR:程序已经无法执行一些功能。
CRITICAL:严重错误,程序可能已无法执行。
默认级别为WARNING,即仅追踪比此级别更高级别的事件
打印到控制台
import logging
logging.warning('I love programming')
logging.info('that is not true')
------------------------------------
WARNING:root:I love programming
可以看到输出只包含WARNING内容,这是因为default level是WARNING。
输出到文件中
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')
运行之后可以看到多出一个 example.log文件,里边记录着三种信息。
这个文件默认是追加的,如果想每次写入都覆盖前边的,可以这样设置:
logging.basicConfig(filename='example.log', filemodel='w', level=logging.DEBUG)
使用带参数的logging
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
---------------------------
WARNING:root:look before you leap!
改变现实信息的格式
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', datefmt=%m/%d/%Y %I:%M:%S %p)
logging.warning('is when this event was logged')