Python logging best practice for reusable modules

2019-02-24 09:30发布

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?

1条回答
聊天终结者
2楼-- · 2019-02-24 09:40

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. Use getLogger based on your module's __name__ and start logging:

     import logging
     logger = logging.getLogger(__name__)
     logger.info( ... )
     logger.debug( ... )
    
  2. 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.

查看更多
登录 后发表回答