python - 如何使用不同的类和导入动态地使用 Python 日志更改文件句柄

标签 python logging configuration

我无法执行动态记录文件句柄更改。

例如,我有 3 个类(class)

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(),它不起作用。

最佳答案

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

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

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

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

Configuring Logging chapter在 Python Logging HOWTO 中。

关于python - 如何使用不同的类和导入动态地使用 Python 日志更改文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839554/

相关文章:

python - 在 python 2.6 中关闭套接字的正确方法是什么?

php - IPN传送失败。 HTTP错误代码500 : Internal Server Error

Eclipse - 更改当前标签的开始和结束标签的背景颜色

java - ThrowableInformation getThrowableStrRep() 的作用是什么?

java - 为什么仅使用 XML 元素定义 log4j 对象不起作用?

configuration - 如何在 nginx 中重用服务器配置?

python - 如何使用 Python 将列表组成的值与字典中的常见项组合起来?

python - 如何比较 Pandas 数据框中的行

python - 模板中的 Django forloop

testing - 运行 Rust cargo test 并让测试运行器将任何日志输出显示到控制台 stdout 或 stderr 的方法有哪些?