分享

多module使用Logging(只要在同一个Python interpreter process)

 小猪窝969 2015-05-09

  上面我曾提到过,所有的对logging.getLogger(‘someLogger’)的调用都会返回同一个对象.这个规则不仅仅在同一个module有效,而且对在同一个Python的解释器进程里面的多个module也有效.而且,应用代码可以在一个module里面定义一个父logger,而在另一个module里面继承这个logger,所有对这个子logger的调用都会转到父logger里面去,如下所示:

下面这个是主模块的代码,

  1. import logging  
  2. import auxiliary_module  
  3. # create logger with "spam_application"  
  4. logger = logging.getLogger("spam_application")  
  5. logger.setLevel(logging.DEBUG)  
  6. # create file handler which logs even debug messages  
  7. fh = logging.FileHandler("spam.log")  
  8. fh.setLevel(logging.DEBUG)  
  9. # create console handler with a higher log level  
  10. ch = logging.StreamHandler()  
  11. ch.setLevel(logging.ERROR)  
  12. # create formatter and add it to the handlers  
  13. formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")  
  14. fh.setFormatter(formatter)  
  15. ch.setFormatter(formatter)  
  16. # add the handlers to the logger  
  17. logger.addHandler(fh)  
  18. logger.addHandler(ch)  
  19. logger.info("creating an instance of auxiliary_module.Auxiliary")  
  20. a = auxiliary_module.Auxiliary()  
  21. logger.info("created an instance of auxiliary_module.Auxiliary")  
  22. logger.info("calling auxiliary_module.Auxiliary.do_something")  
  23. a.do_something()  
  24. logger.info("finished auxiliary_module.Auxiliary.do_something")  
  25. logger.info("calling auxiliary_module.some_function()")  
  26. auxiliary_module.some_function()  
  27. logger.info("done with auxiliary_module.some_function()")  

这个是子模块的代码,

  1. import logging  
  2. # create logger  
  3. module_logger = logging.getLogger("spam_application.auxiliary")  
  4. class Auxiliary:  
  5.     def __init__(self):  
  6.         self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")  
  7.         self.logger.info("creating an instance of Auxiliary")  
  8.     def do_something(self):  
  9.         self.logger.info("doing something")  
  10.         a = 1 + 1  
  11.         self.logger.info("done doing something")  
  12. def some_function():  
  13.     module_logger.info("received a call to /"some_function/"")  

可以看到, 我们在主模块里面定义了一个logger 'spam_application', 并对他进行了配置.

那么在这个解释器进程里面的任何地方去通过getLogger('spam_application')得到的对象都是一样的, 不需要从新定义配置, 可以直接使用.

更方便的是, 你定义任意该logger的子logger, 都可以共享父logger的定义和配置

所谓的父子logger只是简单的通过命名来识别, 任意以'spam_application.'开头的logger都是他的子logger, 例如'spam_application.auxiliary'

这个在实际的开发中, 还是很方便的, 对于一个application,

首先通过logging配置文件编写好这个application所对应的log策略, 可以只生成一个根logger, 比如叫'Project'

然后在Main函数里面, 通过fileConfig加载logging的配置

接着在appliction的任意地方, 不同的模块中, 可以使用Project的子logger, 如Project.UI, Project.Core, 来进行log, 并且不需要反复的定义和配置各个logger.

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多