Disable logging per method/function?

You could create a decorator that would temporarily suspend logging, ala:

from functools import wraps

def suspendlogging(func):
    @wraps(func)
    def inner(*args, **kwargs):
        previousloglevel = log.getEffectiveLevel()
        try:
            return func(*args, **kwargs)
        finally:
            log.setLevel(previousloglevel)
    return inner

@suspendlogging
def my_func1(): ...

Caveat: that would also suspend logging for any function called from my_func1 so be careful how you use it.


The trick is to create multiple loggers.

There are several aspects to this.

First. Don't use logging.basicConfig() at the beginning of a module. Use it only inside the main-import switch

 if __name__ == "__main__":
     logging.basicConfig(...)
     main()
     logging.shutdown()

Second. Never get the "root" logger, except to set global preferences.

Third. Get individual named loggers for things which might be enabled or disabled.

log = logging.getLogger(__name__)

func1_log = logging.getLogger( "{0}.{1}".format( __name__, "my_func1" )

Now you can set logging levels on each named logger.

log.setLevel( logging.INFO )
func1_log.setLevel( logging.ERROR )

You could use a decorator:

import logging
import functools

def disable_logging(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        logging.disable(logging.DEBUG)
        result = func(*args,**kwargs)
        logging.disable(logging.NOTSET)
        return result
    return wrapper

@disable_logging
def my_func1(...):

Tags:

Python

Logging