当前位置: 首页 > 面试题库 >

如何使用不同的类和导入即时使用Python登录更改文件句柄

单嘉泽
2023-03-14
问题内容

我无法即时执行日志文件处理更改。

例如我有3个班级

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什么也不 做:

如果根记录器已经为其配置了处理程序,则此功能不执行任何操作。

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

    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日志记录”操作指南中的“配置日志记录”一章。



 类似资料:
  • 我们的Java应用程序在Logback上使用SLF4J来记录错误消息。在我们的回复中。xml,我们为错误日志定义了一个appender,以及一个指定包层次结构顶层的记录器。 我们正在将记录数据的功能添加到不同的日志文件中。我创建了一个类来处理这个日志记录,我向logback.xml添加了一个新的appender和一个新的logger。新的logger指定了我创建的新类的完全限定包名称(以及addt

  • 问题内容: 例如,我想在一个源文件中同时使用text / template和html / template。但是下面的代码会引发错误。 问题答案: 在规范中阅读有关它的更多信息。

  • 我在Python 3.3项目中有一个名为/models的目录。 从我的我只是做了一个 在我的: 这在我的应用程序中非常有效。 我有一个依赖于另一个模型的模型,例如在我的我需要导入。py。当我这样做时: 我得到错误。 如何从同一模块/目录中的文件A导入类B?

  • 我正在尝试使用log4j在我的tomcat安装的不同文件中记录某些消息,但是尽管它会在我的rootLogger上记录,但它不会在我创建的单独文件上记录。 这是我的log4j.properies文件,其中我尝试使用的文件是dataflow_logging.log: 我的WebService的属性文件: 初始化数据流记录器的方法: 非常感谢你的帮助!

  • 问题内容: 我正在使用pysftp库的函数(https://pysftp.readthedocs.io/en/release_0.2.9/pysftp.html#pysftp.Connection.get_r)从sftp服务器获取目录结构的本地副本。 当远程目录的内容已更改并且我只想获取自上次运行脚本以来已更改的文件时,这种方法是否正确? 该脚本应该能够递归地同步远程目录并镜像远程目录的状态- f

  • 我们目前正在使用SAML2.0和ADFS 2.0为客户门户中的客户在RightNow中实现SSO,但该过程返回错误代码17:“SSO_CONTACT_TOKEN_VALIDATE_FAILED” IdP 使用联系信息(客户的登录名作为断言主体)生成已签名的 SAML 2.0 断言。ADFS 2.0 使用 HTTP POST 绑定提交以下断言: 可能是 SAML 断言中的问题吗?