Logging 模块



很多程序都有记录日志的需求并且日志中包含的信息即有正常的程序访问日志还可能有错误、警告等信息输出python的logging模块提供了标准的日志接口你可以通过它存储各种格式的日志logging的日志可以分为 debug()info()warning()error() and critical() 5个级别下面我们看一下怎么用。

最简单用法

1
2
3
4
5
6
7
8
import  logging
 
logging.warning( "user [alex] attempted wrong password more than 3 times" )
logging.critical( "server is down" )
 
#输出
WARNING:root:user [alex] attempted wrong password more than  3  times
CRITICAL:root:server  is  down

看一下这几个日志级别分别代表什么意思

Level When it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

  

如果想把日志写到文件里也很简单

1
2
3
4
5
6
import  logging
 
logging.basicConfig(filename = 'example.log' ,level = logging.INFO) 
logging.debug( 'This message should go to the log file' )
logging.info( 'So should this' )
logging.warning( 'And this, too' )

其中下面这句中的level=loggin.INFO意思是把日志纪录级别设置为INFO也就是说只有比日志是INFO或比INFO级别更高 的日志才会被纪录到文件里在这个例子 第一条日志是不会被纪录的如果希望纪录debug的日志那把日志级别改成DEBUG就行了。

1
logging.basicConfig(filename = 'example.log' ,level = logging.INFO)

感觉上面的日志格式忘记加上时间啦日志不知道时间怎么行呢下面就来加上!

1
2
3
4
5
6
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 / 12 / 2010  11 : 46 : 36  AM  is  when this event was logged.