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

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

问题描述

我无法即时执行日志记录文件句柄更改.

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

例如,我有 3 个班级

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")

如果我再次尝试 loggin.basicConfig(),它不起作用.

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

推荐答案

确实,logging.basicConfig 如果已经设置了处理程序,什么都不做:

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

请参阅 Python 日志记录 HOWTO 中的配置日志记录一章.

See the Configuring Logging chapter in the Python Logging HOWTO.

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

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