0

I have a main.py:

import logging, sys
logging.basicConfig(
    level=logging.DEBUG, 
    handlers=[logging.FileHandler("test.log"), logging.StreamHandler(sys.stdout)]
)  # log everything to file and stdout
logger = logging.getLogger("main")
logger.info("hello main!")

import thirdparty_module
thirdpary_module.foo()

import my_submodule1

which imports my_submodule1, my_submodule2 ... my_submodule9 that log a few things in DEBUG:

import logging 
logger = logging.getLogger("my_submodule1")
logger.debug("my_submodule1 debug test")

and a third party module thirdparty_module.py which I don't control, but that logs too many things in DEBUG:

import logging, time, threading
logger = logging.getLogger("thirdparty_module")

def foo():
    threading.Thread(target=bar).start()

def bar():
    while True:
        logger.debug(f"thirdparty_module {time.time()}")    # flood!!
        time.sleep(0.1)

Question: how to keep DEBUG logging "ON" for main.py, my_submodule1.py, ..., my_submodule9.py, but avoid thirdparty to log anything in DEBUG?

Note:

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

2

If the example is correct, then you can get thirdparty.logger. Logger objects have propagate attribute - this sets whether logs propagate to the upper loggers and their handlers. By default it's set to True, just switch it to False:

# main.py
...
import thirdparty_module
thirdparty_module.logger.propagate = False
thirdparty_module.foo()
...

Quick test:

import logging
logging.basicConfig(level=logging.DEBUG)

l1 = logging.getLogger()
l2 = logging.getLogger("test")

l2.debug("test") # this prints

l2.propagate = False
l2.debug("test") # this doesn't print
Basj
  • 41,386
  • 99
  • 383
  • 673
h4z3
  • 5,265
  • 1
  • 15
  • 29
  • Thanks @h4z3! Also I tried `thirdparty_module.logger.setLevel(logging.INFO)` in `main.py` and it works too: everything from `thirdparty_module` will be limited to INFO and higher. – Basj Oct 25 '22 at 12:55