Sub topic 9
Filters and adding context to records
This chapter assumes you know loggers, handlers, formatters, and how records propagate up the logger hierarchy. A filter is the fourth part of that pipeline. It can reject a record, and it can also change the record before a handler formats it.
What a filter is
A filter is an object with a filter(record) method. It returns a true value to keep the record and a false value to drop it. You attach filters with addFilter() to a logger or to a handler.
Since Python 3.2 any callable that takes a record works as a filter, so you do not have to subclass logging.Filter. A subclass is still useful when the filter needs configuration or state.
Filters do two jobs:
- Reject records based on anything in the record: level, logger name, message text, or custom attributes.
- Enrich records by setting new attributes on the record object, which a formatter can then use in its format string.
The second job is why filters matter in practice. The formatter only reads attributes. A filter is the place to compute them.
Where filters run
Filters can sit in two places, and the difference causes most filter bugs.
A logger's filters run once, on the logger where the call was made. When a record propagates to a parent, the parent's logger filters are not consulted. Handler filters run for every record that reaches that handler, wherever it came from.
A first filter
This filter attaches a fixed request_id to every record. The handler's formatter then uses it.
import logging
class RequestIdFilter(logging.Filter):
def filter(self, record):
record.request_id = "req-123"
return True
handler = logging.StreamHandler()
handler.addFilter(RequestIdFilter())
handler.setFormatter(logging.Formatter("%(request_id)s %(levelname)s %(message)s"))
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Handling request")This prints req-123 INFO Handling request. The filter always returns True, so it never rejects anything. It only enriches.
Rejecting records
A filter that returns False drops the record for that logger or handler. A common use is splitting output between two streams by level. A handler's level sets only a minimum, so a maximum needs a filter.
import logging
import sys
class MaxLevelFilter(logging.Filter):
def __init__(self, max_level):
super().__init__()
self.max_level = max_level
def filter(self, record):
return record.levelno <= self.max_level
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.addFilter(MaxLevelFilter(logging.INFO))
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(logging.WARNING)
logger = logging.getLogger("myapp")
logger.setLevel(logging.DEBUG)
logger.addHandler(stdout_handler)
logger.addHandler(stderr_handler)
logger.debug("to stdout")
logger.error("to stderr")DEBUG and INFO go to stdout. WARNING and above go to stderr. No record appears twice.
The base logging.Filter("myapp.db") is also worth knowing. It accepts only records from the logger named myapp.db or its descendants, matched by name prefix. It is rarely needed, because a handler attached to that logger does the same job.
Adding context that changes per request
A hardcoded value is not useful. Real context, such as a request ID or a user name, changes while the program runs. The standard tool for this is contextvars. A context variable holds a separate value for each thread and each asyncio task. A filter can read it at the moment a record is handled.
import contextvars
import logging
request_id_var = contextvars.ContextVar("request_id", default="-")
class ContextFilter(logging.Filter):
def filter(self, record):
record.request_id = request_id_var.get()
return True
handler = logging.StreamHandler()
handler.addFilter(ContextFilter())
handler.setFormatter(
logging.Formatter("%(request_id)s %(levelname)s %(message)s")
)
logger = logging.getLogger("myapp")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
def handle(request_id):
token = request_id_var.set(request_id)
try:
logger.info("Handling request")
finally:
request_id_var.reset(token)
handle("req-1")
logger.info("Outside any request")The output is req-1 INFO Handling request, then - INFO Outside any request. The default="-" matters. Without it, get() raises LookupError when no request is active, and logging would fail.
The code that calls logger.info never mentions the request ID. Every module in the call chain gets the context for free.
Alternatives to filters
Filters are not the only way to add attributes. Choose by how widely the context applies.
| Approach | Scope | Use it when |
|---|---|---|
| `extra={...}` in the call | One call | A single message needs a one-off field |
| `logging.LoggerAdapter` | One adapter object | A component always logs with the same fixed context |
| Handler or logger filter | Every record through that handler or logger | Context comes from ambient state such as `contextvars` |
| `logging.setLogRecordFactory` | Every record in the process | Every record needs the attribute, whichever logger or handler is used |
With extra, the keys become attributes on the record. A key that collides with an existing attribute, such as message, asctime, or name, raises KeyError.
Filter behavior to watch for
Logger filters do not apply to child records
This is the most common surprise. A filter on a parent logger does not catch records from its children.
import logging
logging.basicConfig(level=logging.INFO, format="%(name)s: %(message)s")
parent = logging.getLogger("myapp")
child = logging.getLogger("myapp.db")
parent.addFilter(lambda record: "secret" not in record.getMessage())
parent.info("hello")
parent.info("secret token") # dropped by the parent's filter
child.info("secret token") # still printed: parent filters are skipped
root_handler = logging.getLogger().handlers[0]
root_handler.addFilter(lambda record: "secret" not in record.getMessage())
child.info("secret token again") # now dropped by the handler filterTo filter everything that reaches an output, attach the filter to the handler. The lambda is a valid filter because any callable is accepted.
Mutations are shared
All handlers receive the same LogRecord object. If a filter on one handler changes record.msg or record.args, handlers processed later see the changed record. For example, a redaction filter on the console handler would also redact the file output if the file handler runs after it. When handlers need different content, add a separate attribute instead of overwriting existing ones. You can also copy the record with copy.copy(record) and return the copy. Returning a new record from filter is supported from Python 3.12.
Missing attributes cause formatting errors
If the format string uses %(request_id)s and a record has no such attribute, formatting fails. The logging module does not raise into your program. It prints a "--- Logging error ---" traceback to stderr and drops the line. This happens often when the formatter is shared with a handler that has no context filter, or when a third-party library logs through a handler you did not expect. Always set an attribute on every record that reaches a formatter that needs it, as the default="-" above does.
Filters are not inherited
A logger does not copy its parent's filters. Only handlers are found by walking up the hierarchy.
Configuring filters with dictConfig
In dictConfig, filters live in their own filters section and are referenced by name from handlers or loggers. The "()" key names a class or callable that builds the filter.
import contextvars
import logging
import logging.config
request_id_var = contextvars.ContextVar("request_id", default="-")
class ContextFilter(logging.Filter):
def filter(self, record):
record.request_id = request_id_var.get()
return True
config = {
"version": 1,
"disable_existing_loggers": False,
"filters": {"context": {"()": ContextFilter}},
"formatters": {
"ctx": {"format": "%(request_id)s %(levelname)s %(name)s: %(message)s"}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "ctx",
"filters": ["context"],
}
},
"root": {"level": "INFO", "handlers": ["console"]},
}
logging.config.dictConfig(config)
request_id_var.set("req-42")
logging.getLogger("myapp").info("Configured with a filter")If the class lives in another module, give "()" a dotted string such as "myapp.logging_utils.ContextFilter". Any other keys in the filter's entry are passed to its constructor as keyword arguments.
Summary
- A filter returns true to keep a record and false to drop it. It can also set attributes on the record.
- Logger filters apply only to records created through that logger. Handler filters apply to every record that reaches the handler.
- Use
contextvarswith a handler filter to add per-request context without changing call sites. - Records are shared between handlers, so avoid overwriting existing attributes.
- Make sure every record has each attribute your format string uses.
Exercise
You add a filter to the logger "app" that drops messages containing "password". Records logged through "app.auth" still contain the password text in the console output. Why does this happen, and how do you fix it?
Show answer
Logger filters run only for records created by the logger they are attached to. A record from "app.auth" propagates to the handlers of "app" and the root, but the filter on "app" is skipped. Attach the filter to the console handler instead, because handler filters run for every record that reaches the handler.
Exercise
Write a filter class that adds a hostname attribute using socket.gethostname() to each record and always keeps the record. Where should you attach it so records from all loggers carry the attribute, and what must the formatter's format string contain to show it?
Show answer
class HostFilter(logging.Filter): def filter(self, record): record.hostname = socket.gethostname(); return True. Attach it to the handler (or to each handler that uses the format), so that records from every logger that reaches it are enriched. The format string needs %(hostname)s, for example "%(hostname)s %(levelname)s %(message)s".