什么是日志?
日志是一种可以追踪某些软件运行时所发生事件的方法,用来记录程序中重要的消息,可以看做一个对象,所记录的信息看作是它的属
日志的级别
- DEBUG
- INFO
- NOTICE
- WARNING
- ERROR
- CRITICAL
- ALERT
- EMERGENCY
在常用的logging模块中常用的有debug,info,warning,error,critical这五个等级
如何实现日志功能
在python中提供有一个用于记录日志的标准库模块---logging
logging模块
logging模块默认定义了五个日志等级,它允许开发人员自定义其他日志级别,但是由于会导致日志级别的混乱,所以不被推荐在开发供别人使用的库时使用
表中日志等级从上到下依次升高,其信息量从上到下依次减少
logging模块提供了两种记录日志的方式:第一种方式是使用logging提供的模块级别的函数;第二种方式是使用Logging日志系统的四大组件:
先分别输出一条不同日志级别的日志记录:
import logging logging.debug('this is a debug') logging.info('this is a info') logging.warning('this is a warning') logging.error('this is a error') logging.critical('this is a critical')
也可写做:
logging.log(logging.DEBUG,'this is a debug') logging.log(logging.INFO,'this is a info') logging.log(logging.WARNING,'this is a warning') logging.log(logging.ERROR,'this is a error') logging.log(logging.CRITICAL,'this is a critical')
结果为:
WARNING:root:this is a warning
ERROR:root:this is a error
CRITICAL:root:this is a critical
进程已结束,退出代码0
这里,结果依次为日志级别:日志器名称:日志内容,由于debug和info的级别小于logging模块提供的日志记录函数所使用的日志器设置的日志级别warning,所以被丢弃并未打印出来
我们可以将日志记录进行配置后输入到文件中,而不必打印在控制台:
import logging log_format='%(asctime)s-%(levelname)s-%(message)s' logging.basicConfig(level=logging.DEBUG, filename='my.log', format=log_format)
此时,经过配置的五条日志记录将输出到我们创建的my.log文件中
logging模块中定义好的可以用于format格式字符串中字段:
最后我们可以对输入日志记录的日期格式进行设置:
DATE_FORMAT = '%m/%d/%Y %H:%M:%S %p'#设置输出日期时间格式 logging.basicConfig(level=logging.DEBUG, filename='my.log', format=log_format, datefmt=DATE_FORMAT)
结果:
2018-05-23 20:32:28,066-DEBUG-this is a debug 2018-05-23 20:32:28,067-INFO-this is a info 2018-05-23 20:32:28,067-WARNING-this is a warning 2018-05-23 20:32:28,067-ERROR-this is a error 2018-05-23 20:32:28,067-CRITICAL-this is a critical 05/23/2018 20:40:09 PM-DEBUG-this is a debug 05/23/2018 20:40:09 PM-INFO-this is a info 05/23/2018 20:40:09 PM-WARNING-this is a warning 05/23/2018 20:40:09 PM-ERROR-this is a error 05/23/2018 20:40:09 PM-CRITICAL-this is a critical日期显示顺序已变为月日年