Python Logging

更新日期: 2017-08-19 阅读次数: 8045 分类: Python

One of the differences between a great programmer and a bad programmer is that a great programmer adds logging and tools that make it easy to debug the program when things fail. -- Henrik Warne

同一服务的不同功能的日志如何记录

根据 Logging Cookbook 里的解释,可以使用

logging.getLogger("app_name") 

创建一个父 logger,然后在每个功能模块里使用

logging.getLogger("app_name.module_name")

创建不同的子 logger,这样在日志文件中就能通过日期后面跟随的 app_name.module_name 来区分这条日志来自哪个功能模块。这种情况下,推荐在配置文 件中配置父 logger,然后在不同功能模块里获取一个子 logger 即可。

Multiple calls to logging.getLogger('someLogger') return a reference to the
same logger object. This is true not only within the same module, but also
across modules as long as it is in the same Python interpreter process. It is
true for references to the same object; additionally, application code can
define and configure a parent logger in one module and create (but not
configure) a child logger in a separate module, and all logger calls to the
child will pass up to the parent.

但是,这样做有一个前提,即这是在一个进程内运行的不同功能。因为 python 的 logging 只是线程安全的,但是不支持多进程写同一个日志文件。参考:

Logging to a single file from multiple processes

所以,在不同功能处于不同进程时,就只能配置不同的日志文件了。这种情况下,logger 的配置信息还是写到各自的 module 里比较好。

测试代码:

  • https://github.com/sunzhongwei/config/blob/master/Templates/python_logging/settings.py
  • https://github.com/sunzhongwei/config/blob/master/Templates/python_logging/worker.py

参考:

  • [[http://docs.python.org/2/howto/logging-cookbook.html|Logging Cookbook]]
  • tornado 的 log.py

按照日志文件大小 rotate, 并只保留指定数量的日志

参考:

将日志同时输出到 stdout 和日志文件

通常服务端程序是将日志记录到日志文件中,但是调试的时候看日志就很不方便。 最好能够同时输出到 stdout。解决方法:

参考:

Python 2.7 引入的基于字典配置的直观方法

参考:

  • http://docs.python.org/2/howto/logging-cookbook.html#an-example-dictionary-based-configuration

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式