Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing Python logging code

I have a Python application written on the Pyramid framework.

We really take advantage of logging on this ( for debugging ) , using the standard import library.

As we profile stuff on production, it seems that there is quite a bit of overhead from our logging activity. All the string formatting and loops add up. I'd love to remove it, but we can't -- we do actually need to keep it in for testing and will sometimes need to debug on the production environment.

I'm wondering if anyone has effective strategies for minimizing logging as needed , so this code could get "optimized away" during execution on our production environment and simply not run .

For example, under mod_perl, the compiler would "optimize away" statements run under False constants

in psuedocode... ( i haven't touched perl in a long time! )

use constant DEBUG => False ;
if ( DEBUG ) {
      log.debug("stuff here " + string );
}

or

use constant DEBUG => False ;
DEBUG && log.debug("stuff here " + string );

Under those scenarios, the call to log.debug and even the string interpolation would never happen.

Can anyone recommend an effective method of mimicking that behavior under Python ?

like image 669
Jonathan Vanasco Avatar asked Mar 19 '26 10:03

Jonathan Vanasco


2 Answers

Use __debug__. This flag is set to False when Python is run with the -O command line flag, and Python will furthermore optimize out debug code at compile time. I wrote a blog post on it a couple months ago.

like image 128
kindall Avatar answered Mar 20 '26 23:03

kindall


Don't use concatenation when you can use log.debug('stuff here %s', string); the logging module postpones interpolation until actually formatting the string when logging. If the DEBUG log level has been disabled, no interpolation takes place.

You can also test the logging level to avoid gathering expensive logging information unless needed:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())

See the optimization section of the Logging HOWTO.

like image 34
Martijn Pieters Avatar answered Mar 20 '26 23:03

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!