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,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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: logging模块Python标准库中的一个模块,用于记录程序运行时的日志信息。它提供了一种灵活的方式来控制日志记录的级别、格式和输出目标,可以将日志信息输出到控制台、文件、网络等不同的位置。使用logging模块可以帮助我们更好地理解程序的运行情况,快速定位问题并进行调试。在使用logging模块时,我们需要定义一个Logger对象,然后使用它来记录日志信息。Logger对象可以设置多个Handler对象,每个Handler对象可以设置不同的日志级别和输出目标。日志级别包括DEBUG、INFO、WARNING、ERROR和CRITICAL五个级别,级别越高,记录的信息越重要。在记录日志信息时,我们可以使用不同的格式化字符串来控制日志信息的输出格式,例如时间、级别、模块名、函数名等。除了基本的日志记录功能外,logging模块还提供了一些高级功能,例如日志回滚、日志过滤、日志轮换等,可以根据实际需求进行配置。 ### 回答2: logging模块Python内置的一个用于输出日志信息的模块,通过它我们可以记录程序运行时产生的各种信息,帮助我们了解程序运行过程中的动态情况,有助于快速排查问题和系统优化。 logging模块的主要特点: 1.提供了5种不同的日志级别控制,从低到高分别是DEBUG、INFO、WARNING、ERROR、CRITICAL,不同级别的日志信息可以按照需求进行输出和记录。 2.可以灵活配置日志的输出位置和格式,包括控制台输出、文件输出和邮件输出等,还可以通过配置格式化器进行日志信息格式化。 3.支持输出、记录异常信息及堆栈信息等,便于排查问题。 以下是logging模块的一些常用方法及用法: 1. basicConfig():进行一些基本配置,如日志级别、输出格式、输出位置等,通常在程序入口处调用。 2. getLogger():获取一个logger实例,可以用来输出日志信息,常用于创建模块级别的日志记录器。 3. setLevel():设置日志级别,只有比设置级别高的日志才会输出。 4. addHandler():添加处理器,将日志信息发送到指定的输出位置,比如文件、控制台等。 5. Formatter():定义日志信息的格式化方式,可以定义不同的格式化字符串实现不同的输出格式。 6. 异常处理:可以使用try-except语句结合logging模块来记录异常信息及堆栈信息,方便排查问题。 7. 多模块日志处理:使用getLogger()方法可以创建多个记录器,为不同的模块或功能区分开来,方便排查问题。 总之,logging模块Python中非常有用的一个模块,它可以帮助我们记录程序运行中的各种信息,并提供各种定制化的输出方式,有助于提高代码的可读性和可维护性,快速排查问题。同时,也要注意在实际使用中避免频繁输出日志信息导致程序性能下降。 ### 回答3: Python中的logging模块是一个优秀的记录日志的方式,可以将程序中任何需要记录的信息输出到特定的位置,如控制台、文件或者网络。logging模块提供了强大的日志功能,可以将输出日志进行分级、格式化、过滤、存储等多种功能,可以让开发者方便地实现程序日志输出。下面将对logging模块的详细使用进行介绍。 logging模块的主要概念包括Logger、Handler、Formatter。Logger表示一个日志记录器对象,可以设定日志记录级别、输出地点和格式;Handler表示在哪里输出日志,不同Handler可以输出到不同位置;Formatter表示日志输出的格式。 使用logging模块记录日志需要以下步骤: 1. 创建一个Logger对象,用于记录日志信息。Logger对象可以指定名字,如果不指定,会使用rootLogger。 ```python import logging logger = logging.getLogger("mylogger") ``` 2. 设置Logger的级别,只有高于该级别的日志才会输出。默认级别为warning。 ```python logger.setLevel(logging.DEBUG) ``` 3. 创建Handler对象,用于将日志信息输出到指定位置。常用的Handler有StreamHandler(输出到控制台)、FileHandler(输出到文件)、HTTPHandler(输出到网络)等。 ```python stream_handler = logging.StreamHandler() file_handler = logging.FileHandler("log.txt") ``` 4. 设置Handler的级别,如果不设置,默认级别为warning。 ```python stream_handler.setLevel(logging.INFO) file_handler.setLevel(logging.ERROR) ``` 5. 创建Formatter对象,用于确定日志信息的输出格式。 ```python formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') stream_handler.setFormatter(formatter) file_handler.setFormatter(formatter) ``` 6. 将Handler添加到Logger对象中。 ```python logger.addHandler(stream_handler) logger.addHandler(file_handler) ``` 7. 使用Logger对象记录日志。 ```python logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message') ``` 日志级别从高到低为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET。 最后,logging模块还可以进行日志的过滤、日志的旋转等操作,可以根据实际需求进行设置。总的来说,logging模块Python程序提供了一种方便、灵活的日志记录方式,可以帮助开发者更好地了解程序的运行状态,方便地进行调试和问题排查。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值