【问题标题】:Python logging in multiple modulesPython记录多个模块
【发布时间】:2014-12-24 06:49:21
【问题描述】:

我想编写一个可以在多个模块中使用的记录器。我必须能够从一个地方启用和禁用它。而且它必须是可重复使用的。

以下是场景。 switch_module.py

class Brocade(object):
    def __init__(self, ip, username, password):
        ...

    def connect(self):
        ...
    def disconnect(self):
        ...
    def switch_show(self):
        ...

switch_module_library.py

import switch_module

class Keyword_Mapper(object):
    def __init__(self, keyword_to_execute):
        self._brocade_object = switch_module.Brocade(ip, username, password)
        ...
    def map_keyword_to_command(self)
        ...

application_gui.py

class GUI:
    # I can open a file containing keyword for brocade switch
    # in this GUI in a tab and tree widget(it uses PyQt which I don't know)
    # Each tab is a QThread and there could be multiple tabs

    # Each tab is accompanied by an execute button.
    # On pressing exeute it will read the string/keywords from the file
    # and create an object of keyword_Mapper class and call
    # map_key_word_to_command method, execute the command on brocade
    # switch and log the results. Current I am logging the result
    # only from the Keyword_Mapper class.

我遇到的问题是如何编写一个可以随意启用和禁用的记录器 它必须记录到一个文件以及所有三个模块的控制台。

我尝试在 int.py 中编写全局记录器,然后将其导入所有三个模块中 并且必须给出一个通用名称,以便它们登录到同一个文件,但随后 遇到了麻烦,因为有多线程,后来创建了记录器 登录到名称中包含 thread-id 的文件,以便我可以拥有每个日志 每个线程。

如果我需要登录到不同的文件而不是同一个文件怎么办?

我浏览了 python 日志记录文档,但无法获得清晰的图像 关于编写一个可以重用的适当的日志系统。

我已经浏览了这个链接 Is it better to use root logger or named logger in Python

但是由于我以外的其他人使用 PyQt 和多线程创建的 GUI,我无法在这里记录日志。

【问题讨论】:

    标签: python logging


    【解决方案1】:

    我的项目我只使用一个根记录器(我没有时间创建命名记录器,即使它会很好)。因此,如果您不想使用命名记录器,这里有一个快速的解决方案:

    我创建了一个快速设置记录器的函数:

    import logging
    
    def initLogger(level=logging.DEBUG):
        if level == logging.DEBUG:
            # Display more stuff when in a debug mode
            logging.basicConfig(
                format='%(levelname)s-%(module)s:%(lineno)d-%(funcName)s: %(message)s',
                level=level)
        else:
            # Display less stuff for info mode
            logging.basicConfig(format='%(levelname)s: %(message)s', level=level)
    

    我为它创建了一个包,以便我可以在任何地方导入它。

    然后,在我的顶层我有:

    import LoggingTools
    if __name__ == '__main__':
        # Configure logger
        LoggingTools.initLogger(logging.DEBUG)
        #LoggingTools.initLogger(logging.INFO)
    

    根据我是否在调试,我使用相应的语句。

    然后在其他文件中,我只使用日志记录:

    import logging
    class MyClass():
        def __init__(self):
            logging.debug("Debug message")
            logging.info("Info message")
    

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 2017-07-14
      • 2013-03-24
      相关资源
      最近更新 更多