python模块介绍- logging 日志工具

python模块介绍- logging 日志工具

 

目录

项目简介... 1

简介:... 2

应用程序和库中使用Logging3

记录日志到文件... 4

日志文件轮转... 4

日志级别... 5

日志实例命名... 6

项目简介

Python中文库https://bitbucket.org/xurongzhong/python-chinese-library主要基于个人的使用经验,收集一些重要的外部和内部模块的中文教程和实例。发起人是ouyangchongwu#gmail.comxurongzhong@gmail.com 。

欢迎大家加入分享经验。联系方法:xurongzhong#gmail.com, 微博:http://weibo.com/cizhenshi,python及测试开发qq群1:113938272,群2:6089740。

文件下载:

1,   https://bitbucket.org/xurongzhong/python-chinese-library/downloads。 推荐

2,   hg clone克隆所有文件  hg clone https://bitbucket.org/xurongzhong/python-chinese-library

3,   https://bitbucket.org/xurongzhong/python-chinese-library/src 浏览文件,右键点击文件,选另存为下载。

Bug 提交:https://bitbucket.org/xurongzhong/python-chinese-library/issuest

版本管理

版本号

修订发布时间

修订人

备注

V1.0

2013-11-26

ouyangchongwu@gmail.com

初始版本, 由《The Python Standard Library by Example 2011》和《http://docs.python.org/2/howto/logging.html#logging-basic-tutorial》生成。

 

 

 

 

 

 

 

 

 

参考资料:

官方网址: http://docs.python.org/2/library/logging.html

Python模块学习 ---- logging 日志记录(一) http://blog.csdn.net/jgood/article/details/4340740

使用python的logging模块 http://kenby.iteye.com/blog/1162698

Python模块学习——logging http://www.cnblogs.com/captain_jack/archive/2011/01/21/1941453.html

python之强大的日志模块logging http://www.stamhe.com/?p=862

 

 

 

 

 

 

 

 

 

 

 

简介:

功能:python日志工具

月下载量:

Python版本:Python2.3以上。

当前版本:

下载地址:

文档地址:

平台:跨平台

        相关模块:

ConcurrentLogHandler 并发日志处理器,将logging 扩展至多进程,月下载4k左右,推荐

Nonblockingloghandler 非阻塞的logging 月下载1.5k左右

Mailinglogger 邮件日志处理器月下载2k左右

log4django django日志处理器。月下载1.5k左右

graypy       loggingGELF日志处理器。月下载2.5k左右

logutils     Logging 的一系列处理器。月下载4k左右,推荐

 

 

 

 

 

 

 

 

 

 

Logging模块定义了报告应用程序和库错误和状态信息的标准API。

应用程序和库中使用Logging

       应用程序使用logging模块,输出信息到指定的输出通道,可以指定不同的日志级别和不同的输出目的地,可输出日志信息到文件,HTTP GET/ POST,电子邮件(SMTP),通用socket,或者操作系统特定的日志机制。可创建自定义日志目标类特殊处理内置类无法处理的需求。

库开发人员使用logging模块更简单,创建logger实例,使用标准日志级别记录日志即可。

记录日志到文件

使用basicConfig函数即可。

importlogging

 

LOG_FILENAME ='logging_example.out'

logging.basicConfig(filename=LOG_FILENAME,

                    level=logging.DEBUG,

                    )

 

logging.debug('Thismessage should go to the log file')

 

withopen(LOG_FILENAME,'rt')as f:

    body = f.read()

 

print'FILE:'

printbody

 

执行结果:

# python logging_file_example.py

FILE:

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

          basicConfig的参数filemode表明写文件的方式,默认是附加,写新文件的方式可以这样修改:

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

日志文件轮转

importglob

importlogging

importlogging.handlers

 

LOG_FILENAME ='logging_rotatingfile_example.out'

 

# Set up a specificlogger with our desired output level

my_logger =logging.getLogger('MyLogger')

my_logger.setLevel(logging.DEBUG)

 

# Add the log messagehandler to the logger

handler =logging.handlers.RotatingFileHandler(LOG_FILENAME,

                                              maxBytes=100,

                                              backupCount=5,

                                               )

my_logger.addHandler(handler)

 

# Log some messages

for i inrange(20):

    my_logger.debug('i =%d'% i)

 

# See what files arecreated

logfiles =glob.glob('%s*'%LOG_FILENAME)

forfilename inlogfiles:

    printfilename

 

执行结果:

# pythonlogging_rotatingfile_example.py

logging_rotatingfile_example.out

logging_rotatingfile_example.out.4

logging_rotatingfile_example.out.3

logging_rotatingfile_example.out.2

logging_rotatingfile_example.out.1

最新的文件内容总是存储在logging_rotatingfile_example.out中,其次logging_rotatingfile_example.out.1,由此类推。

日志级别

日志分成了如下级别:CRITICAL 50,ERROR 40,WARNING 30,INFO 20,DEBUG 10,UNSET 0。输出时只显示大于日志级别的日志。比如设置为30话,只会显示CRITICAL,ERROR和WARNING的日志。默认的日志级别是WARNING。

importlogging

importsys

 

LEVELS ={'debug':logging.DEBUG,

           'info':logging.INFO,

           'warning':logging.WARNING,

           'error':logging.ERROR,

           'critical':logging.CRITICAL,

           }

 

iflen(sys.argv)>1:

    level_name =sys.argv[1]

    level =LEVELS.get(level_name,logging.NOTSET)

    logging.basicConfig(level=level)

 

logging.debug('Thisis a debug message')

logging.info('Thisis an info message')

logging.warning('Thisis a warning message')

logging.error('Thisis an error message')

logging.critical('Thisis a critical error message')

 

       执行结果:

# pythonlogging_level_example.py debug

DEBUG:root:This is a debugmessage

INFO:root:This is an infomessage

WARNING:root:This is awarning message

ERROR:root:This is an errormessage

CRITICAL:root:This is acritical error message

# pythonlogging_level_example.py info

INFO:root:This is an infomessage

WARNING:root:This is awarning message

ERROR:root:This is an errormessage

CRITICAL:root:This is acritical error message

日志实例命名

前面我们在第2个字段都是输出了root。Logging模块支持层次的不同名字的日志记录器。简单的方法来为每个模块使用一个记录器(logger)。每个子logger继承父类的配置,并发送到日志到父日志记录器。当然,子日志记录也可以有自己独特的配置。

importlogging

 

logging.basicConfig(level=logging.WARNING)

 

logger1 =logging.getLogger('package1.module1')

logger2 =logging.getLogger('package2.module2')

 

logger1.warning('Thismessage comes from one module')

logger2.warning('Andthis message comes from another module')

 

        执行结果:

# pythonlogging_modules_example.py

WARNING:package1.module1:Thismessage comes from one module

WARNING:package2.module2:Andthis message comes from another module

日志还有很多其他的配置:比如格式化,发送到多个目的地,通过socket动态修改日志配置。具体参见python手册。

日志格式定制

日志格式的输出参见:LogRecordattributes, 下面例子输出了时间和日志级别名和日志内容。只有日志内容需要填充。

importlogging

importlogging.handlers

 

log_num =10

logger =logging.getLogger('MyLogger')

logger.setLevel(log_num)

fh =logging.handlers.RotatingFileHandler(

    '../logs/dial_log_server.log',

    maxBytes=10000000,

    backupCount=5,

)

fh.setLevel(log_num)

formatter =logging.Formatter(u'%(asctime)s[%(levelname)s] %(message)s') 

fh.setFormatter(formatter)

logger.addHandler(fh)

 

logger.debug('foorbar')

 

     执行结果:

# ./log_format.py

# cat../logs/dial_log_server.log

2013-11-26 14:03:50,567[DEBUG] foorbar

日志的默认输出格式是ISO8601,可以通过如下方式修改:

importlogging

logging.basicConfig(format='%(asctime)s%(message)s', datefmt='%m/%d/%Y%I:%M:%S %p')

logging.warning('iswhen this event was logged.')

   

     执行结果:

# ./test.py

11/26/2013 02:08:25 PM iswhen this event was logged.

      可见datefmt的格式和time.strftime方法相同。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值