When using logging in python like this
import logging
logging.basicConfig(level=logging.INFO)
logger = None
if <some condition>:
logger = logging.getLogger(__name__)
... some code ...
logger.debug('message')
is it possible to avoid calling logger.debug
if it does not exist without if
statement?
You could construct a wrapper object and use that everywhere:
That being said, this is not specific to Python's logging module. Any variable
var
that can also beNone
will need to be checked before you call a method on it (var.method()
).It may be easier to always define a logger and to simply disable the logging through the logging configuration / settings. That keeps the code clean, all logger calls will succeed but the output won't go anywhere if that particular logger is disabled.
Lastly, you could opt to indeed use an if statement as it's not inherently that much more code: