Muposat
Muposat

Reputation: 1506

Logger to not show INFO from external libaries

I want logger to print INFO messages from all my code but not from 3rd party libraries. This is discussed in multiple places, but the suggested solution does not work for me. Here is my simulation of external library, extlib.py:

#!/usr/bin/env python3
from logging import info

def f():
    info("i am extlib f()")

My module:

#!/usr/bin/env python3
import logging
from logging import info
import extlib

logging.basicConfig(level=logging.INFO)
info("I am mymodule")
extlib.f()

Output:

INFO:root:I am mymodule

INFO:root:i am extlib f()

My attempt to only enable INFO for local module:

#!/usr/bin/env python3
import logging
from logging import info
import extlib

logging.getLogger(__name__).setLevel(logging.INFO)
info("I am mymodule")
extlib.f()

Output: nothing

Desired output:

INFO:root:I am mymodule

What am I doing wrong?

Upvotes: 0

Views: 2611

Answers (1)

bravosierra99
bravosierra99

Reputation: 1371

The problem is that they aren't using the logger class in the external library. If they were then you could filter it out. I'm not certain you can stop them from logging information since they are using the info function call. Here is a workaround though.

Suppressing output of module calling outside library

Update:

here's how you do loggers

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

Upvotes: 2

Related Questions