Python的logging模块提供了灵活的事件日志系统。
1. 模块组成
- __init__.py
- config.py
- handlers.py
- 内置函数print()
- logging.debug()
- logging.info()
- logging.warning() ,另一个warnings模块的warnings.warn()具有相似功能
- logging.error(), logging.exception()
- logging.critical()
import logginglogging.info('I told you so')
logging.warning('%s before you %s', 'Look', 'leap!')
推荐日志文件的格式设置如下:
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='/proj/term1/bbauto/logfiles/messages_stable.log',
filemode='w')
5. 日志级别
日志级别包括CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
默认日志级别WARNING
1) 命令行设置日志级别--log=INFO
2) 代码中设置日志级别
myloglevel = '--log'
numeric_level = getattr(logging, myloglevel.upper(), None)
logging.basicConfig(level=numeric_level, ...)
6. 写日志文件
1) 默认追加日志到example.log文件中
logging.basicConfig(filename='example.log')
2) 每次都从头写新日志到example.log文件中
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
参考链接:
https://docs.python.org/3.5/howto/logging.html
https://docs.python.org/3.5/library/logging.html
https://github.com/python/cpython/tree/3.5/Lib/logging
https://docs.python.org/3.5/howto/logging-cookbook.html