python - 在哪里配置日志记录?

标签 python logging project

我想知道在哪里配置和初始化与日志记录模块相关的东西?

例如,我写了一些类,我想在方法执行时记录一些信息。我应该配置登录初始化 或模块顶部的类:

# LOGGING STUFF <--- Should be here ? 

class SomeClass:

    def __init__(self):
        # class stuff
        # LOGGING STUFF <--- Or should be here ? 

    def some_method(self):
        # method stuff
        # LOGGING SOME INFO    

    def some_method2(self):
        # method stuff
        # LOGGING SOME INFO

最佳做法是什么?

最佳答案

日志包有两个用途,辅助作者生产日志和辅助用户消费日志。你可能会同时扮演这两个角色,但分别考虑它们会帮助你编写干净、易于理解的代码。
作者的担忧
作者应该在正确的级别实例化记录器:

  • 包记录器应该放在包中 __init__文件。注意 __name__ 的使用,它将解析为 SomePackage :
      import logging
      package_logger = logging.getLogger(__name__)
    
  • 模块顶部的模块记录器。注意 __name__ 的力量!在这里它将解析为 SomePackage.SomeModule .
      import logging
      module_logger = logging.getLogger(__name__)
    
  • 类级别记录器可以放在类定义的顶部。请注意 __name__ 的强大功能使用 getLogger 和 __qualname__ 增强!记录器名称将是 SomePackage.SomeModule.SomeClass .此外,不是 _class_logger 中的下划线表示它是供内部使用的。:
      class SomeClass:
          _class_logger = logging.getLogger(__name__).getChild(__qualname__)
    
  • 类中的实例记录器 __init__ .使用 ID 生成唯一标识符。注意 stupend ......你明白了。记录器名称将是 SomePackage.SomeModule.SomeClass.<large_unique_number> :
      class SomeClass:
          def __init__(self):
              self._instance_logger = logging.getLogger(__name__).getChild(self.__class__.__name__).getChild(str(id(self)))
    

  • 这些名称可能不适合您的应用程序。例如,您可能想要一个从其中一个实例化参数派生的实例记录器。但是,您仍然应该致力于在正确的级别上控制您的记录器。
    用户关注
    配置处理程序是用户的工作。通常,作者会确保默认情况下没有任何处理程序处于事件状态。 logging.basicConfig会将所有警告级别及以上的日志记录转储到标准错误。
    import SomePackage
    import logging
    
    logging.basicConfig()
    
    请记住,您可以使用 logging.getLogger() 来访问作者定义的相同记录器。
    from SomePackage import SomeModule
    import logging
    
    """
    module_logger debug to a file. Will capture all 
    child loggers as well if used i.e class_logger and 
    instance_logger
    """
    h = logging.FileHandler('debug')
    h.setLevel('DEBUG')
    SomeModule.module_logger.addHandler(h)
    
    """
    class_logger warning to stderr. Will capture all child loggers
    as well if used i.e instance_logger Note: No need to import
    SomeClass to access it's logger as Logger keeps track of them in
    a dictionary. Typically the prefered approach if your not
    actually using the class.
    """
    h = logging.StreamHandler()
    getLogger('SomePackage.SomeModule.SomeClass').addHandler(h)
    
    如果你通过直接调用它们来调试你自己的模块,你可能有一个 def main()他们应该进去。这可确保包用户不会收到意外的日志文件或控制台消息。
    加分
    如果在多个级别使用记录器,则从现有的派生更 Pythonic。
    module_logger = logging.getLogger(__name__)
    
    class SomeClass:
        _class_logger = module_logger.getChild(__qualname__)
    
        def __init__(self):
            self._instance_logger = self._class_logger.getChild(str(id(self)))
    

    关于python - 在哪里配置日志记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388844/

    相关文章:

    javascript - 检查特定年龄

    python - 电子邮件 "Date"标题应该是发件人的本地时间还是 UTC?

    python - Python 中的二进制线性规划求解器

    python - 为什么 __getattr__ 不能与 __exit__ 一起使用?

    python - 如果logging.config.dictConfig()不影响现有记录器,那么它有什么意义?

    android - Eclipse 项目资源管理器上出现未知错误

    project-management - 您使用什么工具来管理变更请求和错误报告

    python - 了解 torch.nn.Parameter

    python - Django Celery 日志记录最佳实践

    reactjs - 登录 Reactjs