How can I strip Python logging calls without commenting them out? How can I strip Python logging calls without commenting them out? python python

How can I strip Python logging calls without commenting them out?


What about using logging.disable?

I've also found I had to use logging.isEnabledFor if the logging message is expensive to create.


Use pypreprocessor

Which can also be found on PYPI (Python Package Index) and be fetched using pip.

Here's a basic usage example:

from pypreprocessor import pypreprocessorpypreprocessor.parse()#define nologging#ifdef nologging...logging code you'd usually comment out manually...#endif

Essentially, the preprocessor comments out code the way you were doing it manually before. It just does it on the fly conditionally depending on what you define.

You can also remove all of the preprocessor directives and commented out code from the postprocessed code by adding 'pypreprocessor.removeMeta = True' between the import and parse() statements.

The bytecode output (.pyc) file will contain the optimized output.

SideNote: pypreprocessor is compatible with python2x and python3k.

Disclaimer: I'm the author of pypreprocessor.


I've also seen assert used in this fashion.

assert logging.warn('disable me with the -O option') is None

(I'm guessing that warn always returns none.. if not, you'll get an AssertionError

But really that's just a funny way of doing this:

if __debug__: logging.warn('disable me with the -O option')

When you run a script with that line in it with the -O option, the line will be removed from the optimized .pyo code. If, instead, you had your own variable, like in the following, you will have a conditional that is always executed (no matter what value the variable is), although a conditional should execute quicker than a function call:

my_debug = True...if my_debug: logging.warn('disable me by setting my_debug = False')

so if my understanding of debug is correct, it seems like a nice way to get rid of unnecessary logging calls. The flipside is that it also disables all of your asserts, so it is a problem if you need the asserts.