Sub topic 9
Filters and adding context to records
This chapter assumes you know loggers, handlers, and formatters, and how a LogRecord moves from a logger to its handlers. You should also be comfortable writing a small class that inherits from another.
What a filter does
A filter is an object with a filter(record) method. It runs on each LogRecord before the record is processed further. If the method returns a false value, the record is dropped. If it returns a true value, the record continues.
A filter can do two jobs:
- Decide whether a record is kept.
- Change the record, for example by adding attributes.
The second job is how you add context such as a request ID to every line without changing each logging call.
Adding context with a filter
The filter below attaches request_id to each record. The formatter then uses it in its format string.
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 drops anything. It only adds an attribute.
Where to attach a filter
You can attach a filter to a logger or to a handler. The difference matters.
| Attached to | Runs for | Notes |
|---|---|---|
| A logger | Records created by that logger | Not run for records from child loggers that propagate up |
| A handler | Every record that reaches that handler | Includes records propagated from child loggers |
Because of this, put context filters on the handler. A filter on the myapp logger would not run for a record created by myapp.db. Only a handler's filters see every record that reaches it.
Filtering records out
Returning False drops the record for that logger or handler. This example keeps only records that do not come from a noisy library.
import logging
class DropNoisy(logging.Filter):
def filter(self, record):
return not record.name.startswith("noisy")
handler = logging.StreamHandler()
handler.addFilter(DropNoisy())
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(handler)
logging.getLogger("noisy.client").info("Dropped")
logging.getLogger("myapp").info("Kept")Only Kept is printed. Since Python 3.2 a filter can also be a plain function or any callable that takes a record, so a class is not required.
Filters in the processing order
Common errors
- Forgetting to return a value. A
filtermethod that ends withoutreturngivesNone, which counts as false, so every record is dropped. - Putting a context filter on a logger and expecting child loggers to be covered.
- Overwriting an existing attribute such as
nameormessageon the record. Choose attribute names that do not collide with built-inLogRecordfields. - Putting slow work, such as a database lookup, inside
filter. It runs for every record.
Exercise
A filter that sets record.user = "bob" is attached to the logger myapp. A message is logged through myapp.db, and the handler's format uses %(user)s. Why does this fail, and how do you fix it?
Show answer
Filters attached to a logger run only for records created by that logger. Records from the child myapp.db propagate to the handler without passing through the myapp logger's filters, so user is missing and formatting fails. Attach the filter to the handler instead, because the handler sees every record that reaches it.
Exercise
Write a filter class that keeps only records at WARNING level or above.
Show answer
class WarningsOnly(logging.Filter): def filter(self, record): return record.levelno >= logging.WARNING