【问题标题】:Pass logger instance to class将记录器实例传递给类
【发布时间】:2010-04-08 07:16:28
【问题描述】:

我在我的项目中使用了一个开源 Python 库。该库使用日志记录类记录大量信息。 ...但我看不到输出或将其记录到文件中。我知道我必须创建一个记录器实例并向它添加一个文件处理程序或一个控制台处理程序,但是我怎样才能将此记录器实例传递给类?这是我将要使用的类的 init sn-p。

class Periscope:
        ''' Main Periscope class'''

        def __init__(self):
                self.config = ConfigParser.SafeConfigParser({"lang": "en"})
                if is_local:
                        self.config_file = os.path.join(bd.xdg_config_home, "periscope", "config")
                        if not os.path.exists(self.config_file):
                                folder = os.path.dirname(self.config_file)
                                if not os.path.exists(folder):
                                        logging.info("Creating folder %s" %folder)
                                        os.mkdir(folder)
                                logging.info("Creating config file")
                                configfile = open(self.config_file, "w")
                                self.config.write(configfile)
                                configfile.close()
                        else:
                                #Load it
                                self.config.read(self.config_file)

                self.pluginNames = self.listExistingPlugins()
                self._preferedLanguages = None

有什么帮助吗?

谢谢大家。

【问题讨论】:

    标签: python logging


    【解决方案1】:

    最简单的方法是在logging 模块中使用basicConfig 函数。 docs 是这样说的:

    通过使用默认格式化程序创建 StreamHandler 并将其添加到根记录器来为日志记录系统进行基本配置。如果已为根记录器定义了任何处理程序,则该函数不执行任何操作。如果没有为根记录器定义处理程序,函数 debug()、info()、warning()、error() 和 critical() 将自动调用 basicConfig()。

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

    logging 模块的设计方式是将配置与创建日志消息分开,因此无需访问记录器实例。

    【讨论】:

      【解决方案2】:

      尝试将级别设置为尽可能低的级别 (DEBUG)。这将启用所有日志级别,并且应该为您提供所有日志消息。进行默认配置的最简单方法是使用 basicConfig()

      import logging    
      logging.basicConfig(level=logging.DEBUG, filename='/path/to/mylog.log')
      

      如果您使用的库没有覆盖日志配置,这应该足以让消息进入日志文件。如果您知道库使用的记录器的名称,则可以专门为库设置级别:

      logging.getLogger("periscope").setLevel(logging.DEBUG)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 2011-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多