Logging

python中 logging的使用详解

 更新时间:2017年10月25日 08:39:18   作者:Wanna_Go  

这篇文章主要介绍了python中 logging的使用,非常不错,具有参考借鉴价值,需要的朋友可以参考下

日志是用来记录程序在运行过程中发生的状况,在程序开发过程中添加日志模块能够帮助我们了解程序运行过程中发生了哪些事件,这些事件也有轻重之分。

根据事件的轻重可分为以下几个级别:

DEBUG: 详细信息,通常仅在诊断问题时才受到关注。整数level=10

INFO: 确认程序按预期工作。整数level=20

WARNING:出现了异常,但是不影响正常工作.整数level=30

ERROR:由于某些原因,程序 不能执行某些功能。整数level=40

CRITICAL:严重的错误,导致程序不能运行。整数level=50

默认的级别是WARNING,也就意味着只有级别大于等于的才会被看到,跟踪日志的方式可以是写入到文件中,也可以直接输出到控制台。

输出到控制台

下面是一个小例子通过将日志输出到控制台的方法:

1

2

3

4

import logging

logging.warning('Watch out!') # 将输出到控制台

logging.info('I told you so') # 不会输出

logging.error("an error occurrence!") #将输出到控制台

输出结果

1

2

WARNING:root:Watch out!

ERROR:root:an error occurrence

输出到文件中

新开一个python解释器,确保不是上面代码的session

1

2

3

4

5

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

这个时候控制台上面就没有了输出,文件example.log中的内容

1

2

3

DEBUG:root:This message should go to the log file

INFO:root:So should this

WARNING:root:And this, too

假定需要手动调整日志的级别,我们可以在命令行以参数的形式传入--log=INFO,在代码中可以采用下面的处理方式

1

2

3

4

5

# 输入参数 --log=DEBUG or --log=debug

numeric_level = getattr(logging, loglevel.upper(), None)#返回10,否则None

if not isinstance(numeric_level, int):

 raise ValueError('Invalid log level: %s' % loglevel)

logging.basicConfig(level=numeric_level, ...)

变量的日志

Python客栈送红包、纸质书

使用格式化字符串的方式,为变量添加日志

1

2

import logging

logging.warning('%s before you %s', 'Look', 'leap!')

自定义日志格式

我们还可以根据我们的需求自定义输出模板

1

2

3

4

5

import logging

logging.basicConfig(format='%(asctime)s: %(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')

输出

1

2

3

2017-10-24 14:03:53,671: DEBUG: This message should appear on the console

2017-10-24 14:03:53,690: INFO: So should this

2017-10-24 14:03:53,694: WARNING: And this, too

内部实际传入的为一个字典,%(key)为字典的key。

上面是python logging模块的一些基本用法, 已经能够满足我们的许多需求,下面简单介绍下logging的一些高级用法。在logging模块中主要包括logger,handlers,filter,formatters,这几个组件

logger:提供了应用接口,供程序使用
handlers:用来将logger创建的log 发送到相应的目的地
filter:为要输出的日志提供了更细粒度的设置
formatters:设置最终的输出格式

下面是这几个组件配合使用的例子

1

2

3

4

5

6

7

8

9

10

11

12

13

import logging

logger = logging.getLogger('logger_name')# 创建logger对象

logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler()# 创建 console handler 并设置级别为debug

handler.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# 创建输出格式

handler.setFormatter(formatter)# 为handler添加fromatter

logger.addHandler(handler)# 将handler添加到 logger

logger.debug('debug message')# 'application' code

logger.info('info message')

logger.warn('warn message')

logger.error('error message')

logger.critical('critical message')

输出结果:

2017-10-24 16:50:43,127 - logger_name - DEBUG - debug message
2017-10-24 16:50:43,138 - logger_name - INFO - info message
2017-10-24 16:50:43,141 - logger_name - WARNING - warn message
2017-10-24 16:50:43,144 - logger_name - ERROR - error message
2017-10-24 16:50:43,148 - logger_name - CRITICAL - critical message

小应用案例

下面是自己定义的一个日志处理方法,既能够写入到文件中(滚动保存近15天的日志,日志格式app.log, app.log.1, app.log.2),又能输出到控制台。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

import logging

from logging.handlers import TimedRotatingFileHandler

class MylogHandler(logging.Logger):

 def __init__(self,name,level="DEBUG",stream=True,files=True):

  self.name = name

  self.level = level

  logging.Logger.__init__(self,self.name,level=self.level)

  if stream:

   self.__streamHandler__(self.level)

  if files:

   self.__filesHandler__(self.level)

 def __streamHandler__(self,level=None):

  handler = TimedRotatingFileHandler(filename=self.name+".log", when='D', interval=1, backupCount=15)

  handler.suffix = '%Y%m%d.log'

  handler.setLevel(level)

  formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')

  handler.setFormatter(formatter)

  self.addHandler(handler) #将hander添加到logger上

 def __filesHandler__(self,level=None):

  handler = logging.StreamHandler()

  formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')

  handler.setFormatter(formatter)

  handler.setLevel(level)

  self.addHandler(handler)

if __name__ == '__main__':

 log = MylogHandler('test')

 log.info('this is a my log handler')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值