2

I have frequent doubts when I write python modules and classes, specifically:

Where/how should I put the main flag that controls logging and where/how to create the logger,

  • Should it be at the module level? ---thus need to have some global MyLogger almost everywhere inside each method.

  • Should it be an argument passed to methods and/or classes? Perhaps to decide if a method or class needed it or not, maybe I could use the **args stars magic, with call like myMethod(..., logger=Mylogger)?

  • Where should I define/set the I_logged_something flag? (...or should I rely on the if MyLogger: MyLogger.log('something'))

  • What about when the class or module is imported?

What is the Pythonic way of logging? How do you use the logging tools?

1 Answer 1

5

You use logging everywhere, regardless.

In your modules, use:

import logging log = logging.getLogger(__name__) 

and log away. Use the different levels (log.info(), log.debug(), log.error(), etc.) depending on what type of message you are logging.

Your main entry point then configures the logging module output. That can include completely disabling any output, or directing debug information to a file, but logging errors to the console.

Your modules do not need to care, the logging module handles configuration of the output handlers and formatting as global state.

Sign up to request clarification or add additional context in comments.

1 Comment

More precisely, you handle logging configuration of handlers, levels etc. by calling appropriate logging code from your main entry point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.