Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging best practice for reusable modules intended to be included with other code

Tags:

python

logging

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?

like image 261
deadcode Avatar asked Feb 12 '23 03:02

deadcode


1 Answers

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.

like image 182
Dan Lenski Avatar answered Feb 14 '23 17:02

Dan Lenski