2

Coming from Java, it is advisable to wrap a log.debug with

if (log.isDebugEnabled())
    log.debug("blah blah blah "+someObject+" more blahs than you can blah at"):

Is there a similar reson to do this in python? Or does python handle strings differently?

bharal
  • 15,461
  • 36
  • 117
  • 195
  • Out of curiosity, *why* is it advisable? Maybe then we could tell you if those reasons apply to Python. –  Jun 28 '13 at 09:53
  • 1
    Is there a ... yes! Here, an SO question for java: http://stackoverflow.com/questions/963492/in-log4j-does-checking-isdebugenabled-before-logging-improve-performance. Effectively, it is a typical simple performance optimization. Ugh, i guess my trivial example wasn't quite right... let me fix – bharal Jun 28 '13 at 09:55
  • @bharal, thanks for clarifying what do you really mean - I've updated the answer, recheck it, please. – alecxe Jun 28 '13 at 11:36

2 Answers2

3

The suggested answer ignores the overhead of string concatenation and any heavy method calls.

So this:

log.debug("blah blah blah "+someObject+" more blahs than you can blah at")

Will cost the string contact, even in ERROR logging level.

Different languages/loggers manage that in different ways, checking for isDebugEnabled() or isEnabledFor() are good best practices.

Of course, you shouldn't pre-optimize if this is not relevant, like anything in this world.

JAR.JAR.beans
  • 9,668
  • 4
  • 45
  • 57
1

There is no need for additional checks. Just configure your logging level:

>>> import logging
>>> root = logging.getLogger()
>>> root.setLevel(logging.INFO)
>>> root.addHandler(logging.StreamHandler())
>>> logging.error("test")
test
>>> logging.debug("test")
>>>

Again, there is no need for additional checks (the source code taken from logging/__init__.py):

class Logger(Filterer):
    ...
    def debug(self, msg, *args, **kwargs):
        """
        Log 'msg % args' with severity 'DEBUG'.

        To pass exception information, use the keyword argument exc_info with
        a true value, e.g.

        logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
        """
        if self.isEnabledFor(DEBUG):
            self._log(DEBUG, msg, args, **kwargs)

As you can see logging itself makes the check.

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195