Reputation: 1157
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?
Upvotes: 2
Views: 324
Reputation: 1121904
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.
Upvotes: 5