Logning 模块定义了很多方法和类,为application和libraries实现了一个灵活的事件记录系统。
Task you want to perform |
The best tool for the task |
Console 中展示 |
print() |
程序正常运行时的事件 |
logging.info() (or logging.debug() for very detailed output for diagnostic purposes) |
关于某个运行时事件,发出警告 |
warnings.warn() in library code if the issue is avoidable and the client application should be modified to eliminate the warning logging.warning() if there is nothing the client application can do about the situation, but the event should still be noted |
抛出异常 |
Raise an exception |
Report suppression of an error without raising an exception (e.g. error handler in a long-running server process) |
logging.error(), logging.exception() or logging.critical() as appropriate for the specific error and application domain |
log 的等级:
Level |
When it’s used |
DEBUG |
诊断错误时候的详细信息 |
INFO |
程序正常运行,用来确认信息 |
WARNING |
程序正常运行,但是警告某个未来可能发生的问题,或者未预料的事情 |
ERROR |
严重问题,某些功能无法实现 |
CRITICAL |
严重错误,程序无法运行 |
默认Level 是WARNING,默认只有WARNING,ERROR, CRITICAL会被追踪。
importlogging
logging.debug("debug")
logging.info('info')
logging.warning("warning")
logging.error('error')
logging.critical("critical")
输出:
D:\software\python-2.7.9\python.exe D:/Django-workspace/hello_world/Log/Log_Text.py
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
basicConfig函数传入两个参数,一个是文件名,一个是Log Level
logging.basicConfig(filename="example.log",level=logging.DEBUG) logging.debug("debug") logging.info('info') logging.warning("warning") logging.error('error') logging.critical("critical")
运行后目录下生成example.log文件。
打开后:
设的Level 是DEBUG所以,五个LEVEL的信息都打印出来了。
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
如果不设置filemode 参数,多次运行某脚本,每次运行的message会都附加在exmaple.log后。设置后,多次运行脚本,exmaple.log 都会被清除
当程序中有多个模块时,该怎么记录日志?
# myapp.py
importlogging
importmylib
defmain():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished')
if __name__ =='__main__':
main()
# mylib.py
importlogging
defdo_something():
logging.info('Doing something')
运行myapp.py ,结果如下:
INFO:root:Started
INFO:root:Doing something
INFO:root:Finished
用%s的格式,将变量作为参数,
importlogging
logging.warning('%s before you %s','Look','leap!')
结果:
WARNING:root:Look before you leap!
为展示时间,需要在格式日志中加入‘%(asctime)s’
importlogging
logging.basicConfig(format='%(asctime)s%(message)s')
logging.warning('is when this event was logged.')
结果:
2010-12-12 11:41:42,612 is when this event was logged.
默认是ISO8601格式展示,我们可以提供datefmt 参数给basicConfig函数来改变格式
importlogging
logging.basicConfig(format='%(asctime)s%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')