您的位置:首页 > 编程语言 > Python开发

python log学习笔记

2015-06-12 10:30 501 查看
logging 模块为应用程序提供灵活的手段来记录事件,错误,警告和调试信息。这些信息额可以进行收集、筛选、写入文件、放给系统日志等操作,甚至还可以通过网络发送给远程计算机。

日志记录级别

每个日志记录由一些文本和指示其严重性的相关级别组成。级别包含符号名称和数字值,如下所示。

级别描述
CRITICAL50关键错误/消息
ERROR40错误
WARING30警告消息
INFO20通知消息
DEBUG10调试
NOTSET0无级别

Logger对象

为了发出日志消息,必须获得Logger对象,这时可以使用:

getLogger([logname])

这个函数,如果logname是空,那么取的是与根记录器(root)相关的Logger对象。

处理器对象

1.内置处理器

handlers.FileHandle(filename,mode,encoding, delay)

将日志消息写入文件filename。mode是打开文件时使用的文件模式,默认为‘a’。encoding是文件编码.delay是一个布尔标志,如果为True,就会延迟打开日志文件,知道发出收条日志消息。

handlers.RotatingFileHandler(filename, mode, maxByte, backupCount, encoding, delay)

将日志消息写入文件filename。但是,如果文件的大小超出maxBytes指定的值,那么它将被备份为filename.1,然后打开一个新的日志文件filename。

handlers.HTTPHandle(host, url, method)

使用HTTP的GET或POST方法将日志消息上传到一台HTTP服务器。method为GET或POST.

2.处理器配置

以下方法用于为每个Handler对象h配置它自己的级别和筛选。

h.setLevel(level)

设置要处理消息的阈值。level是一个数字代码,如ERROR或CRITICAL

h.addFilter( filt )

给处理器添加Filter对象 filt

消息格式化

当日志记录调用中对Handler对象进行格式化时,这些对象就会发出日志消息。但是,有事需要给消息添加另外的上下文信息,如时间戳,文件名,行号等。

1.Formatter对象

要修改日志消息的格式,必须首先创建Formatter对象。

Formatter( fmt , datefmt )

fmt为消息提供提供格式字符串。 datefmt是一个与time.strftime()函数兼容的日期格式字符串。

比较常用的用法:

format = logging.Formatter("%(levelname)-10s % (asctime)s % (message)s")

crit_hand = logging.StreamHandler(sys.stderr)
crit_hand.setFormatter(format)


日志记录配置

将应用程序设置为使用logging模块,一般包括下面几个基本步骤。

1. 使用getLogger()函数创建各种Logger对象。正确设置消息处理的level,如INFO,DEBUG等等

2. 通过实例化各类处理器(FileHanler、StreamHandler、SocketHandler等)创建Handler,并设置正确的level

3. 创建消息Formatter对象,并使用setFormatter()方法把他们附加给Handler对象。

4. 使用addHandler()方法将Handler对象附件给Logger对象。

配置相关的代码可以写在logconfig.py这种文件中,然后在应用程序的主程序中导入它,然后其他的地方只要getLogger就行了,全局使用。

下方有大片干货来袭

但是觉得用配置文件的方式更加方便可读:

;logcofig.ini
;
;Configuration file for setting up logging

;The following sectios provide names for Logger,Handler,and Formatter
;objects that will be configured later in the file.

[loggers]
keys=root

[handlers]
keys=Info_Handler,Debug_Handler,Error_Handler,console

[formatters]
keys=format

[logger_root]
level=DEBUG
handlers=Info_Handler,Debug_Handler,Error_Handler,console

[formatter_format]
format=%(process)s %(asctime)s - %(name)s - %(levelname)s - %(message)s

[handler_Info_Handler]
class=logging.handlers.RotatingFileHandler
level=INFO
formatter=format
args=('log/myproject-info.log','a',60000000,4,)

[handler_Debug_Handler]
class=logging.handlers.RotatingFileHandler
level=DEBUG
formatter=format
args=('log/myproject-debug.log','a',60000000,4,)

[handler_Error_Handler]
class=logging.handlers.RotatingFileHandler
level=ERROR
formatter=format
args=('log/myproject-error.log','a',60000000,4,)

[handler_console]
class=StreamHandler
level=INFO
formatter=format
args=(sys.stdout,)


使用下面的语句即可使用log功能:

import logging
from logging import config

logger = logging.getLogger()
config.fileConfig('logconfig.ini')

logger.info("hello mutex86")


Warning!

在python 2.7中,logging模块仅仅是线程安全的,也就是说多进程代码不能直接这样使用。下面是官方给出的解决办法.

If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler , and have a separate process which implements a socket server which reads from the socket and logs to file.

参考资料

《python参考手册》第四版
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python log