如何更改文件句柄与Python日志记录的飞行与不同的类和导入 [英] How to change filehandle with Python logging on the fly with different classes and imports

查看:264
本文介绍了如何更改文件句柄与Python日志记录的飞行与不同的类和导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法执行即时记录档案处理变更。



例如,我有3个课程



one.py

  import logging 
一个():
def __init __(self,txt =?):
logging.debug(嘿,我是类一,我说:%s%txt)

two.py

  import logging 
class Two():
def __init __(self,txt =?):
logging.debug (嘿,我是第二类,我说:%s%txt)

code> config.py

  import logging 
class Config():
def __init __(self,logfile = None):
logging.debug(Reading config)
self.logfile(logfile)
pre>

myapp

 从一个导入一个
从两个导入两个
从配置导入配置
导入日志记录

#set默认日志
logging.basicConfig
level = logging.getLevelName(DEBUG),
format ='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename =无


logging.info(从stdout开始)

o =一个(txt =STDOUT)
c = Config =/ tmp / logfile)

#这里必须是改变日志配置和设置filehandler的代码

t = One(txt =This must be on文件,而不是STDOUT)



如果我尝试 loggin.basicConfig / code>再次,它不工作。

解决方案

确实, logging.basicConfig


此函数用于创建处理程序。


您需要将替换当前根记录器上的处理程序:

  import logging 

fileh = logging.FileHandler('/ tmp / logfile','a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileh.setFormatter (hdlr)中的hdlr [:]:#删除所有旧的处理程序
log.removeHandler(hdlr)

log = logging.getLogger()
log.addHandler(fileh)#设置新处理程序

http://docs.python.org/2/howto/logging.html#configuring-logging =nofollow>在Python记录HOWTO中配置日志记录章。


I cannot perform an on-the-fly logging fileHandle change.

For example, I have 3 classes

one.py

import logging
class One():
    def __init__(self,txt="?"):
        logging.debug("Hey, I'm the class One and I say: %s" % txt)

two.py

import logging
class Two():
    def __init__(self,txt="?"):
        logging.debug("Hey, I'm the class Two and I say: %s" % txt)

config.py

import logging
class Config():
    def __init__(self,logfile=None):
        logging.debug("Reading config")
        self.logfile(logfile)

myapp

from one import One
from two import Two
from config import Config
import logging

#Set default logging
logging.basicConfig( 
    level=logging.getLevelName(DEBUG), 
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename=None
)

logging.info("Starting with stdout")

o=One(txt="STDOUT")
c=Config(logfile="/tmp/logfile")

# Here must be the code that change the logging configuration and set the filehandler

t=One(txt="This must be on the file, not STDOUT")

If I try loggin.basicConfig() again, it doesn't work.

解决方案

Indeed, logging.basicConfig does nothing if a handler has been set up already:

This function does nothing if the root logger already has handlers configured for it.

You'll need to replace the current handler on the root logger:

import logging

fileh = logging.FileHandler('/tmp/logfile', 'a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileh.setFormatter(formatter)

log = logging.getLogger()  # root logger
for hdlr in log.handlers[:]:  # remove all old handlers
    log.removeHandler(hdlr)
log.addHandler(fileh)      # set the new handler

See the Configuring Logging chapter in the Python Logging HOWTO.

这篇关于如何更改文件句柄与Python日志记录的飞行与不同的类和导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆