Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore specific logging line temporarily

Tags:

python

logging

I have a method called import_customers() which loads csv-like data.

This methods logs to log-level INFO.

In one case I want to avoid this logging.

I see several ways:

Variant 1: a new kwarg like do_logging=True which I can switch to false.

Variant 2: Use some magic context which ignores this line.

with IgnoreLoggingContext() as context:
    import_customers()

How could I implement IgnoreLoggingContext()?

If you think V1 is better, then please leave a comment.

like image 542
guettli Avatar asked Aug 20 '19 08:08

guettli


1 Answers

It depends on your need. If you want to disable the whole logging, it would be the simplest:

from contextlib import contextmanager
import logging


@contextmanager
def IgnoreLoggingContext():
    root = logging.getLogger()
    origin_level = root.getEffectiveLevel()
    root.setLevel(logging.WARNING) # Or whatever you want
    yield
    root.setLevel(origin_level)

with IgnoreLoggingContext():
    do_something()

Or you can pass a variable to the manager to specify which logger to disable:

@contextmanager
def IgnoreLoggingContext(name):
    logger = logging.getLogger(name)
    origin_level = logger.getEffectiveLevel()
    logger.setLevel(logging.WARNING) # Or whatever you want
    yield
    logger.setLevel(origin_level)
like image 164
Sraw Avatar answered Sep 28 '22 11:09

Sraw