统计

留言簿(1)

DB

Others

QA

Tech Website

阅读排行榜

评论排行榜

【转】Python的标准logging模块

Configuring Logging

Programmers can configure logging either by creating loggers, handlers, 
and formatters explicitly in a main module with the configuration methods listed above (using Python code), or by creating a logging config file. The following code is an example of configuring a very simple logger, a console handler, and a simple formatter in a Python module:

程序员可以显示地通过在主模块里面用上面列出的配置方法创建loggers,handlers和formatters的方式,或者,创建一个logging的配置文件的方式来配置logging.以下是一个非常简单的配置logger的例子,一个python模块里面包含了一个命令行handler和一个简单的formmater:

import logging

 

#create logger

logger 
= logging.getLogger("simple_example")

logger.setLevel(logging.DEBUG)

#create console handler and set level to debug

ch 
= logging.StreamHandler()

ch.setLevel(logging.DEBUG)

#create formatter

formatter 
= logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - 

   
%(message)s")

#add formatter to ch

ch.setFormatter(formatter)

#add ch to logger

logger.addHandler(ch)

 

#"application" code

logger.debug(
"debug message")

logger.info(
"info message")

logger.warn(
"warn message")

logger.error(
"error message")

logger.critical(
"critical message")

Running this module 
from the command line produces the following output:

在在字符界面下运行上面的命令产生以下输出:

jmjones@bean:
~/logging $ python simple_logging_module.py

2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message

2005-03-19 15:10:26,620 - simple_example - INFO - info message

2005-03-19 15:10:26,695 - simple_example - WARNING - warn message

2005-03-19 15:10:26,697 - simple_example - ERROR - error message

2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message

The following Python module creates a logger, handler, 
and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects:

跟例子差不多,以下的Python模块创建了一个logger,一个handler和一个formatter,这里仅仅换了换名字:

import logging

import logging.config

 

logging.config.fileConfig(
"logging.conf")

 

#create logger

logger 
= logging.getLogger("simpleExample")

 

#"application" code

logger.debug(
"debug message")

logger.info(
"info message")

logger.warn(
"warn message")

logger.error(
"error message")

logger.critical(
"critical message")

Here 
is the logging.conf file:

这里是logging.conf文件:

[loggers]

keys
=root,simpleExample

 

[handlers]

keys
=consoleHandler

 

[formatters]

keys
=simpleFormatter

 

[logger_root]

level
=DEBUG

handlers
=consoleHandler

 

[logger_simpleExample]

level
=DEBUG

handlers
=consoleHandler

qualname
=simpleExample

propagate
=0

 

[handler_consoleHandler]

class=StreamHandler

level
=DEBUG

formatter
=simpleFormatter

args
=(sys.stdout,)

 

[formatter_simpleFormatter]

format
=%(asctime)s - %(name)s - %(levelname)s - %(message)s

datefmt
=

The output 
is nearly identical to that of the non-config-file-based example:

输出跟没有配置文件的例子完全一样:

jmjones@bean:
~/logging $ python simple_logging_config.py

2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message

2005-03-19 15:38:55,979 - simpleExample - INFO - info message

2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message

2005-03-19 15:38:56,055 - simpleExample - ERROR - error message

2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

The config file approach has a few advantages over the Python code approach. The first 
is the separation of configuration and code. The second is the ability of noncoders to easily modify the logging properties. The third is the really cool listen() method, which causes the application to listen on a socket for new configurations--and will update configurations at runtime without forcing you to restart the application!

用配置文件的方法比直接在Python代码里面写有几个好处.第一个好处是配置和代码的分离.第二个好处是即使看不懂程序也能方便的更改logging的属性.第三个好处是”最酷的listen()方法”,用这个方法可以让你的应用程序在一个socket上监听新的配置信息 
-- 可以直接在运行时改变配置而用不着重启你的应用~!

Here 
is a slight modification of the previous config file-based script:

这里是一个简单的基于上面配置文件的脚本:

#!/usr/bin/env python

 

import logging

import logging.config

import time

import os

 

#specify logging config file

logging.config.fileConfig(
"logging.conf")

 

#create and start listener on port 9999

= logging.config.listen(9999)

t.start()

 

#create logger

logger 
= logging.getLogger("simpleExample")

 

#watch for existence of file named "f"

#loop through the code while this file exists

while os.path.isfile('f'):

    logger.debug(
"debug message")

    logger.info(
"info message")

    logger.warn(
"warn message")

    logger.error(
"error message")

    logger.critical(
"critical message")

    time.sleep(
5)

 

#cleanup

logging.config.stopListening()

t.join()

That was simple enough. Unfortunately, figuring out what format the config file needs to be took some investigation. The only useful information that I found 
in the Python Standard Library Reference documentation was in the logging configuration section under the listen() method:

够简单了吧!不幸地是,理解这个配置文件需要进行些研究.我仅仅在Python的标准库文档logging配置一节里面的listen()方法找到一点有用的信息:

Logging configurations will be sent as a file suitable 
for processing by fileConfig().

Logging配置会作为一个能被fileConfig()方法处理的文件发送.

Pushing a filename did 
not work. Pushing the contents of a config file did not work. I had to dig into the source a little. The docstring for the logging socket server's handle() method is:

用文件名不行,用配置文件的内容也不行.我不得不深入一下源码logging socket服务器的handler()方法的docstring是这样写的:

Handle a request.

 

Each request 
is expected to be a 4-byte length,

followed by the config file. Uses fileConfig() to do the

grunt work. 

处理一个请求.

每个请求都应该是4
-byte长,后面跟一个配置文件.用fileConfig()方法完成剩下的工作.

This struck me as a bit odd. Does that mean you can send lengths only 
for config files of up to 9,999 bytes? Converting the length of the config file to a string did not work either. I looked farther down in the source code of the handle() method. Aaahh. It does a struct.unpack(), so the socket expects the first 4 bytes to be packed binary data. I tried it this way and it worked. The following snippet of code sends the contents of the file named on the command line to localhost:9999:

这让我感到有些奇怪.难道说只能发送长度大于9,999bytes的配置文件吗?而且把一个配置文件的内容转化成一个字符串也是不起作用.我又看了一下handler()方法的源码.哈.它其实做了struct.unpack()!,所以socket才要求前面4个bytes打包二进制的数据.我用这种方式重新试了一下,可以了.下面的代码片断把指定的文件内容通过字符界面发送到了localhost:9999端口:

#!/usr/bin/env python

 

import socket

import sys

import struct

 

HOST 
= 'localhost'

PORT 
= 9999

= socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print "connecting"

s.connect((HOST, PORT))

print "connected"

data_to_send 
= open(sys.argv[1], "r").read()

print "sending length"

s.send(struct.pack(
">L", len(data_to_send)))

print "sending data"

s.send(data_to_send)

print "closing"

s.close()


文章转自:http://crazier9527.iteye.com/blog/290026
参考:
http://crazier9527.iteye.com/blog/290024
http://crazier9527.iteye.com/blog/290018
http://crazier9527.iteye.com/blog/290027

posted on 2011-08-12 14:49 XXXXXX 阅读(1196) 评论(0)  编辑  收藏 所属分类: Python


只有注册用户登录后才能发表评论。


网站导航: