码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习之logging模块

时间:2015-03-20 14:39:33      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:python   logging   

Python自带日志处理模块logging

默认的日志级别有DEBUG,INFO,WARNING,ERROR,CRITICAL,对应的函数是debug(),info(),warning(),error()和critical()


In [490]: import logging

In [491]: LOG_FILENAME=‘/tmp/example.log‘

In [492]: logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

In [493]: logging.debug(‘This message should go to the log file‘)


查看/tmp/example.log的内容

$ cat /tmp/example.log 
DEBUG:root:This message should go to the log file

不断执行

logging.debug(‘This message should go to the log file‘)

/tmp/example.log会不断地刷新



日志轮转

In [639]: import glob

In [640]: import logging

In [641]: import logging.handlers

In [642]: LOG_FILENAME=‘/tmp/logging_rotatingfile_example.out‘

In [643]: my_logger=logging.getLogger(‘MyLogger‘)

In [644]: my_logger.setLevel(logging.DEBUG)

In [645]: handler=logging.handlers.RotatingFileHandler(LOG_FILENAME,maxBytes=20,backupCount=5)

In [646]: my_logger.addHandler(handler)

In [648]: for i in range(20):
    my_logger.debug(‘i=%d‘ % i)
   .....:     
   .....:     

In [650]: logfiles=glob.glob(‘%s*‘ %LOG_FILENAME)

In [651]: for filename in logfiles:
   .....:     print filename
   .....:     
   .....:     
/tmp/logging_rotatingfile_example.out.1
/tmp/logging_rotatingfile_example.out.2
/tmp/logging_rotatingfile_example.out.5
/tmp/logging_rotatingfile_example.out.3
/tmp/logging_rotatingfile_example.out.4
/tmp/logging_rotatingfile_example.out


最近的日志文件总是名为logging_rotatingfile_example.out,一旦大小达到maxBytes设置的20字节,就将轮转。


logging模块最重要的一个功能就是可以根据设置的不同的日志级别输出不同的日志信息。






参考文档:

https://docs.python.org/2.6/library/logging.html#configuration-file-format


本文出自 “Linux SA John” 博客,请务必保留此出处http://john88wang.blog.51cto.com/2165294/1622501

Python学习之logging模块

标签:python   logging   

原文地址:http://john88wang.blog.51cto.com/2165294/1622501

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!