当前位置:   article > 正文

python logging模块的多文件应用_python logger模块多文件调用

python logger模块多文件调用

概述

有的时候需要在一个python程序中生成多个log文件。
本文对logging进一步封装,展示如何在一个程序中使用logging模块打印两个log文件来记录不同类型的信息。
注意logging模块是线程安全的,可以在多线程环境中使用。

完整的代码

  1. #!/usr/bin/env python2.7
  2. # -*- coding:utf-8 -*-
  3. import logging, logging.handlers
  4. class LogMgr:
  5. def __init__ (self, logpath, markpath):
  6. self.LOG = logging.getLogger('log')
  7. loghdlr1 = logging.handlers.RotatingFileHandler(logpath,"a", 0, 1)
  8. fmt1 = logging.Formatter("%(asctime)s %(threadName)-10s %(message)s", "%Y-%m-%d %H:%M:%S")
  9. loghdlr1.setFormatter(fmt1)
  10. self.LOG.addHandler(loghdlr1)
  11. self.LOG.setLevel(logging.INFO)
  12. self.MARK = logging.getLogger('mark')
  13. loghdlr2 = logging.handlers.RotatingFileHandler(markpath,"a", 0, 1)
  14. fmt2 = logging.Formatter("%(message)s")
  15. loghdlr2.setFormatter(fmt2)
  16. self.MARK.addHandler(loghdlr2)
  17. self.MARK.setLevel(logging.INFO)
  18. def error(self, msg):
  19. if self.LOG is not None:
  20. self.LOG.error(msg)
  21. def info(self, msg):
  22. if self.LOG is not None:
  23. self.LOG.info(msg)
  24. def debug(self, msg):
  25. if self.LOG is not None:
  26. self.LOG.debug(msg)
  27. def mark(self, msg):
  28. if self.MARK is not None:
  29. self.MARK.info(msg)
  30. def main():
  31. global log_mgr
  32. log_mgr = LogMgr("mylog","mymark")
  33. log_mgr.error('[mylog]This is error log')
  34. log_mgr.info('[mylog]This is info log')
  35. log_mgr.debug('[mylog]This is debug log')
  36. log_mgr.mark('[mymark]This is mark log')
  37. if __name__ == "__main__":
  38. main()
'
运行

执行结果


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/963150
推荐阅读
相关标签
  

闽ICP备14008679号