Python 日志入门 Logging Basic Tutorial


Python在标准库中提供logging的主要好处是使自己的代码和第三方库的代码的logging能融合在一起。

什么时候使用logging

  1. 程序正常的在终端中输出: print()
  2. 报告在普通操作时发生的事件(如状态监控、故障侦测、用户日志等): logging.info(), logging.debug()输出非常详细的异常原因
  3. 发出一个关于特殊运行时事件的警告:
    1. warnings.warn():如果问题是可避免的,并且客户端需要修改以排除的警告。有追踪栈。
    2. logging.warning():如果客户端对此无能为力,但是仍然需要被注意的事件。仅仅出现文本的提示
  4. 在运行时,某些时间发生后给出一个错误告知: 抛出异常 Raise an exception
  5. 不用抛出异常的方式报告错误被封锁:logging.error()logging.exception()logging.critical()。用上述方法程序会继续执行下去。
In [7]: def foo(): 
   ...:     print('begin') 
   ...:     logging.error('error') 
   ...:     print('end') 
   ...:                                                                         

In [8]: foo()                                                                   
begin
ERROR:root:error
end

In [9]: def foo(): 
   ...:     print('begin') 
   ...:     logging.exception('exception') 
   ...:     print('end') 
   ...:                                                                                                                                             

In [10]: foo()                                                                  
begin
ERROR:root:exception
NoneType: None
end

In [11]: def foo(): 
    ...:     print('begin') 
    ...:     logging.critical('exception') 
    ...:     print('end') 
    ...:                                                                        

In [12]: foo()                                                                  
begin
CRITICAL:root:exception
end

事件的严重程度

标准的事件严重性从低到高分别为:

  1. DEBUG:详细的信息,典型应用于关注诊断程序。
  2. INFO:证明程序是正常的,按期望运行的日志。
  3. WARNING:有程序运行异常的迹象(如numpy的除0警告,但得数是np.inf),或表明程序在不旧的将来会发生异常(如:硬盘存储空间低)。但程序依然如预期的工作。
  4. ERROR:因为一些更严重的问题,程序不能执行一些函数。(如网站某些接口不能请求,但是其他接口可以)
  5. CRITICAL:一个严重的错误,指明程序可能不能继续运行。

默认的等级是WARNING,只有这个等级和比这个等级更严重的事件(Event)才会被追踪,除非logging包被配置成其他样子。

被追踪的事件可以使用不同的方式进行处理,最简单的方式是将追踪记录输出到终端。另一种常见的方式是写入到文件当中。

当等级设定为WARNING

In [1]: import logging 
   ...: logging.basicConfig(filename='example.log',level=logging.WARNING) 
   ...: logging.debug('This message should go to the log file') 
   ...: logging.info('So should this') 
   ...: logging.warning('And this, too')                                        

In [2]: logging.warning('haha')                                                 

In [3]: cat example.log                                                         
WARNING:root:And this, too
WARNING:root:haha

当等级设定为DEBUG

In [1]: 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')                                        

In [2]: cat example.log                                                         
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

basicConfig()的调用必须要早于debug()、info()等的调用。因为这个调用是一个一次性的调用(one-off),只有第一个logging的调用会执行basicConfig()

通过指定filemode来控制example.log是追加写还是覆盖写等等

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

定义消息输出的格式

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')

这样输出时就不会带有root

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

控制输出格式的文档:https://docs.python.org/3.6/library/logging.html#logrecord-attributes

在日志中显示时间和日期

import logging
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或RFC3339,用datefmt来控制时间日期的输出, 控制格式和time.strftime()相同

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.

摘录并翻译自python3.6.8官方文档:https://docs.python.org/3.6/howto/logging.html#logging-basic-tutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值