`
crazier9527
  • 浏览: 993969 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Python的标准logging模块(3)

阅读更多

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,handlersformatters的方式,或者,创建一个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

t = 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才要求前面4bytes打包二进制的数据.我用这种方式重新试了一下,可以了.下面的代码片断把指定的文件内容通过字符界面发送到了localhost:9999端口:

#!/usr/bin/env python

 

import socket

import sys

import struct

 

HOST = 'localhost'

PORT = 9999

s = 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()

分享到:
评论

相关推荐

    python的logging模块

    用python写程序的,作为一个完整的项目而言,必须要有日志模块,而python的logging模块为我们提供了这么一种很好的机制,很方便的解决了这个问题。

    python的logging模块.pdf

    详解python的日志模块logging和django中对logging模块的使用

    python logging 模块

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而...

    python中logging模块

    转载于https://www.cnblogs.com/Nicholas0707/p/9021672.html,支持正版

    详解Python中logging日志模块在多进程环境下的使用

    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行...这篇文章给大家主要介绍了在Python中logging日志模块在多进程环境下的使用,需要的朋友可以参考借鉴,下面来一起看看吧。

    python 日志 logging模块详细解析

    主要介绍了python 日志 logging模块 详细解析,本文通过实例代码给大家介绍的非常详细,对大家的工作或学习具有一定的参考借鉴价值,需要的朋友可以参考下

    Python使用logging模块实现打印log到指定文件的方法

    主要介绍了Python使用logging模块实现打印log到指定文件的方法,结合实例形式分析了Python logging模块的原理及相关日志输出操作技巧,需要的朋友可以参考下

    Python日志logging模块功能与用法详解

    本文实例讲述了Python日志logging模块功能与用法。分享给大家供大家参考,具体如下: 本文内容: logging模块的介绍 logging模块的基础使用 logging模块的扩展使用 logging中的Filter 使用配置文件配置logging...

    详解使用python的logging模块在stdout输出的两种方法

     使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志直接输出到标准输出std.out中。 实现  logging模块可以有两种方法实现该功能: 方案一:basicconfig import ...

    Python logging模块handlers用法详解

    主要介绍了Python logging模块handlers用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Python中内置的日志模块logging用法详解

    Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志...

    python日志logging模块使用方法分析

    本文实例讲述了python日志logging模块使用方法。分享给大家供大家参考,具体如下: 一、从一个使用场景开始 开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件 import logging # 创建一个logger ...

    python使用logging模块发送邮件代码示例

    主要介绍了python使用logging模块发送邮件代码示例,具有一定借鉴价值,需要的朋友可以参考下

    python logging日志模块以及多进程日志详解

    python的logging模块提供了灵活的标准模块,使得任何Python程序都可以使用这个第三方模块来实现日志记录。python logging 官方文档 logging框架中主要由四个部分组成: Loggers: 可供程序直接调用的接口 Handlers:...

    解读python logging模块的使用方法

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 1.可以通过设置不同的日志等级,在release版本中只输出重要信息,...

    Python logging模块原理解析及应用

    主要介绍了Python logging模块原理解析及应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics