打算与其他代码一起包含的可重用模块的Python日志记录最佳做法 [英] Python logging best practice for reusable modules intended to be included with other code

查看:55
本文介绍了打算与其他代码一起包含的可重用模块的Python日志记录最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可重用的Python模块(如果重要的话,适用于Python 2.7).我想知道对于希望将我的模块包含在具有自己的日志记录方法的更大框架中的其他人而言,日志记录方面的最佳实践是什么.

I'm developing a reusable Python module (for Python 2.7 if it matters). I am wondering what the best practices are with regard to logging for others who wish to include my module in a larger framework which has its own logging approach.

是否有一种标准的方法可以在模块中设置日志记录,以使用外部调用程序定义的任何记录器?

Is there a standard way to set up logging within my module to use whatever loggers an external calling program has defined?

推荐答案

这是一篇很棒的博客文章,概述了一些最佳实践,我尝试将这些最佳实践作为自己的实践:http://eric.themoritzfamily.com/learning-python-logging.html

Here is a great blog post that outlines some best practices, which I have tried to adopt as my own: http://eric.themoritzfamily.com/learning-python-logging.html

他详细介绍了所有细节和原理,但本质上可以归结为几个简单的原理.

He goes through all the details and rationale, but essentially it comes down to a couple simple principles.

  1. 根据模块的__name__使用getLogger并开始记录:

 import logging
 logger = logging.getLogger(__name__)
 logger.info( ... )
 logger.debug( ... )

  • 不要在模块中定义处理程序或配置适当的日志级别,因为它们可能会干扰您所想到的外部调用程序".您(或您的用户)可以根据需要在主应用程序代码中为所有子模块设置处理程序和所需级别的日志记录详细信息.

  • Don't define handlers or configure the appropriate log-level in your module, because they may interfere with the "external calling program" you have in mind. You (or your users) can set up the handlers and the desired level of logging detail for all the sub-modules as needed, in the main application code.

    这篇关于打算与其他代码一起包含的可重用模块的Python日志记录最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆