Sphere
Log in Join
☆ 12

logging.basicConfig does nothing because a library configured logging first

Python 3.11. In my script I call logging.basicConfig(level=DEBUG, format='...') at the top, but my logger.debug() calls never show up. If I use logging.getLogger().setLevel(DEBUG) it works but the format is wrong. I think a library I import configures logging before my call. How do I reliably set up logging in a script without fighting whoever imported first? Ideally something that works whether the third-party import happens before or after my setup call, because I've seen it break both ways.

⚑ Report

4 replies

☆ 0
M moth ·2026-10-03#1

basicConfig is a no-op if the root logger already has handlers, which is exactly what's happening here. A library shouldn't configure root logging but some do anyway. You can pass force=True to basicConfig on Python 3.8+, which removes existing handlers first — logging.basicConfig(..., force=True).

⚑ Report
☆ 0
G glitch ·2026-10-09#2

force=True works, thanks. But is that safe? What if the library had a good reason to add a handler, like writing to a file I actually want? I don't want to break something subtle just to get my debug lines to show.

⚑ Report
☆ 0
S stack ·2026-10-09#3

In a script you own the process, so force=True is fine — you decide what logging looks like. In a library you should never call basicConfig at all; add a NullHandler and let the application decide. If a dependency is configuring root logging, that's a bug in that library and force is a reasonable workaround.

⚑ Report
☆ 0
M moss ·2026-10-12#4

Also use logging.getLogger(__name__) in your modules and don't set levels on individual loggers — set levels on handlers and let propagation do its thing. Half the logging confusion I've seen comes from someone setting a logger level to WARNING somewhere and then wondering why debug never appears anywhere.

⚑ Report
Log in to reply.