Intercept Standard Logging¶
Your own code uses Logust, but the libraries you depend on (urllib3, httpx, sqlalchemy, uvicorn, ...) log with the standard logging module. By default, those messages go to logging's own handlers, with a different format, and they skip your Logust files, rotation and JSON output.
This recipe routes everything logged with logging through Logust, so all your logs end up in the same place, with the same format. 🎉
The one-liner¶
Call intercept_logging() from logust.contrib:
import logging
from logust.contrib import intercept_logging
intercept_logging()
logging.info("Hello from the standard library")
db_logger = logging.getLogger("myapp.db")
db_logger.warning("Slow query: %.2f s", 1.73)
Every logging call, from your code or from any library, now goes to Logust:
The %-style arguments of logging ("%.2f s", 1.73) are applied by logging before the message reaches Logust, so they keep working as before.
Empty caller fields
Look at the ::0 in the middle. The default format shows the caller as {name}:{function}:{line}, but records forwarded from logging don't carry those fields: they are empty, and the line is 0.
If most of your logs come from logging, use a format without the caller fields, as in the next section.
A format for intercepted records¶
Replace the default handler with one whose format doesn't use {name}, {function} or {line}:
import logging
import sys
from logust import logger
from logust.contrib import intercept_logging
logger.remove()
logger.add(sys.stderr, format="{time} | {level:<8} | {message}")
intercept_logging()
logging.getLogger("myapp.db").warning("Slow query: %.2f s", 1.73)
You can read more about formats in Formatting and about replacing the default handler in Handlers and Sinks.
How it works¶
intercept_logging() does three things:
- It sets the handlers of the root
logginglogger to a singleInterceptHandler. - It sets the root level to
level(logging.DEBUGby default, so every record is forwarded). - It removes the handlers of every
logginglogger that already exists and makes them propagate to the root.
From then on, each logging record travels up to the root logger, and InterceptHandler hands it to Logust with:
- The level name of the record (
"INFO","WARNING", ...). - The message, already formatted by
logging(record.getMessage()). - The traceback, when the record has
exc_info(for example fromlogging.exception()).
After that, it is a normal Logust message: the target's patchers run before it goes to your handlers, with their levels, formats, filters, rotation and JSON output. This includes message and exception redaction configured with patch() or configure(patcher=...). Intercepted exceptions also follow each handler's backtrace and diagnose options.
Tip
Call intercept_logging() after any code that configures logging itself, for example after logging.basicConfig() in a library or framework you use. It only resets the loggers that exist at the moment you call it.
The full signature is:
level: the minimumlogginglevel forwarded.loggingdrops lower records before they reach Logust.target: the Logust logger that receives the records.Nonemeans the globallogger. See Tag intercepted records.
Manual setup with InterceptHandler¶
If you want more control, install the handler yourself. InterceptHandler is a normal logging.Handler, so you can use it anywhere logging takes one:
import logging
from logust.contrib import InterceptHandler
logging.basicConfig(handlers=[InterceptHandler()], level=logging.INFO, force=True)
logging.getLogger("myapp").info("Routed by a handler you installed yourself")
logging.getLogger("myapp").debug("Below INFO, so the stdlib drops it")
Here logging itself drops the DEBUG message, because of level=logging.INFO.
Note
force=True makes basicConfig() replace any handlers the root logger already has. Without it, basicConfig() does nothing if the root logger is already configured.
You can also attach InterceptHandler to a single logger instead of the root:
Silence a noisy library¶
Intercepted records are matched against the logging logger name for logger.disable(). So you can turn off a library by its logger name:
import logging
from logust import logger
from logust.contrib import intercept_logging
intercept_logging()
logger.disable("urllib3")
logging.getLogger("urllib3.connectionpool").debug("Starting new HTTPS connection")
logging.getLogger("myapp").info("Your own logs still go through")
logger.disable("urllib3") drops records from urllib3 and every urllib3.* logger. You can learn more about these rules in Logging in Libraries.
Custom logging levels¶
Some code defines its own logging levels, like 35. Logust needs to know the level by name to forward the record.
Danger
If a logging record has a level that Logust doesn't know, InterceptHandler raises ValueError: Invalid log level, and the exception propagates to the code that made the logging call.
This happens with:
- A number without a name:
log.log(35, "...")gives the level name"Level 35". - A name registered only in
logging:logging.addLevelName(35, "NOTICE").
To make it safe, register the same name in both places, before the first message:
import logging
from logust import logger
from logust.contrib import intercept_logging
logging.addLevelName(35, "NOTICE")
logger.level("NOTICE", no=35, color="cyan")
intercept_logging()
logging.getLogger("myapp").log(35, "Disk usage is at 91%")
The built-in logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) always work. Read more about logger.level() in Custom Levels.
Tag intercepted records¶
You can pass a bound logger as target. Its context is added to every intercepted record, so you can tell them apart from your own logs:
import logging
from logust import logger
from logust.contrib import intercept_logging
logger.add("app.json", serialize=True)
intercept_logging(target=logger.bind(source="stdlib"))
logging.getLogger("myapp").info("Tagged so you can tell it apart")
logger.info("Logged with logust directly")
The console looks as usual:
And app.json has the source field only on the intercepted record:
{"time":"2026-10-06 11:57:44.733","level":"INFO","message":"Tagged so you can tell it apart","extra":{"source":"stdlib"}}
{"time":"2026-10-06 11:57:44.733","level":"INFO","message":"Logged with logust directly","name":"__main__","function":"<module>","line":11}
InterceptHandler(target=...) takes the same argument.
You can also pass a patched logger, such as target=logger.patch(redact), to apply that patcher to intercepted records. Values from an active contextualize() block are available to both the patcher and the sinks; bound values take precedence over contextualized values, and the patcher's changes are applied last.
Recap¶
intercept_logging()sends everyloggingrecord, from your code and from libraries, to Logust.- Call it after other code has configured
logging. - For finer control, use
InterceptHandlerwithbasicConfig()or on a single logger. - Intercepted records have no caller fields, so prefer a format without
{name}:{function}:{line}. logger.disable("libname")silences a library by itslogginglogger name.- Register custom
logginglevels in Logust with the same name, or they raiseValueError.