Source code for smarter.lib.logging.filters

"""
Logging filters for the Smarter application.

This module provides custom logging filters for use with the Smarter platform's logging configuration.
The primary filter included is :class:`HealthCheckFilter`, which suppresses log records generated by
health check endpoints (such as ``/healthz/`` or ``/readiness/``) to reduce log noise and focus on
meaningful application events.

**Classes:**

- :class:`HealthCheckFilter`: a logging filter that excludes uvicorn's access log records of health
  check requests. It can be used in Django or standard Python logging configurations.
- :class:`AsyncioShieldedCancelFilter`: a logging filter that excludes asyncio's ``CancelledError``
  errors from a shielded future, which a client that disconnects in the middle of a request causes
  under uvicorn.
- :class:`AccessLogQueryFilter`: a logging filter that masks the sensitive query parameters, such
  as a chat's ``session_key``, in uvicorn's access log records.

**Example:**

To use the health check filter in a Django logging configuration::

    LOGGING = {
        'filters': {
            'health_check': {
                '()': 'smarter.lib.logging.filters.HealthCheckFilter',
            },
        },
        'handlers': {
            'default': {
                'class': 'logging.StreamHandler',
                'filters': ['health_check'],
            },
        },
        ...
    }

Uvicorn access log entries whose normalized path is one of the health check paths (as defined in
``health_check_urls``) will be suppressed by this filter.
"""

import asyncio

from smarter.common.mixins import SmarterHelperMixin

# The module, not the smarter.common.utils package, which imports much more: Django loads these
# filters while it configures logging, before its apps are ready.
from smarter.common.utils.utils import mask_url_query
from smarter.lib import logging


[docs] class HealthCheckFilter(logging.Filter, SmarterHelperMixin): """ Logging filter to suppress log records for health check endpoints. This filter is designed to be used with Python's logging framework to automatically exclude log entries generated by health check endpoints (such as ``/healthz/`` or ``/readiness/``) from application logs. This helps reduce log noise and keeps logs focused on meaningful events. The filter inspects only uvicorn's access log records (logger ``uvicorn.access``). It takes the request path from the record's arguments, strips its leading and trailing slashes and lowercases it, and suppresses the record (does not emit it) if the result is exactly one of the ``health_check_urls``. A path that merely contains a health check path, e.g. ``/api/healthz/extra/``, is emitted. Inherits from :class:`SmarterHelperMixin` to provide access to shared configuration and helpers. **Attributes:** - ``health_check_urls`` (``list[str]``): the normalized health check paths, without slashes and in lower case, e.g. ``["readiness", "healthz"]``, from :attr:`~smarter.common.mixins.helper_mixin.SmarterHelperMixin.health_check_urls`. **Example:** To use this filter in a Django logging configuration:: LOGGING = { ... 'filters': { 'health_check': { '()': 'smarter.lib.logging.filters.HealthCheckFilter', }, }, 'handlers': { 'default': { 'class': 'logging.StreamHandler', 'filters': ['health_check'], }, }, ... } The filter will then suppress uvicorn's access log entries for requests whose normalized path is one of the ``health_check_urls``. """
[docs] def filter(self, record: logging.LogRecord) -> bool: """ Determine whether a log record should be emitted based on health check URLs. This filter inspects the log record's path argument and excludes any log entries that match one of the configured health check URLs. This is typically used to suppress noisy log entries generated by health check endpoints (such as ``/healthz/`` or ``/readiness/``) in application logs. The list of health check paths is provided by the ``health_check_urls`` attribute, which holds normalized paths (e.g. ``"healthz"``, ``"readiness"``). The log path is normalized by stripping leading/trailing slashes and lowercasing it, then compared with them exactly, so that variants like "/healthz", "/healthz/", "/HEALTHZ/" or "healthz" all match. Records of other loggers, and records whose path can't be read, are emitted. Example ``record.args`` for a Uvicorn access log: .. code-block:: python ( "192.168.9.92:60250", # client address "GET", # HTTP method "/healthz/", # path "1.1", # HTTP version 200, # status code ) **Example:** >>> filter = HealthCheckFilter() >>> class DummyRecord: ... name = "uvicorn.access" # Simulate a Uvicorn access log record ... args = ("127.0.0.1:12345", "GET", "/healthz/", "1.1", 200) >>> filter.health_check_urls ['readiness', 'healthz'] >>> filter.filter(DummyRecord()) False >>> DummyRecord.args = ("127.0.0.1:12345", "GET", "/api/v1/resource/", "1.1", 200) >>> filter.filter(DummyRecord()) True :param record: The log record to be filtered. :returns: False if the record is a uvicorn access log of a health check path, and should be suppressed; True otherwise (the log record will be emitted). """ # belt & suspenders check to be extra sure we only filter Uvicorn # access logs and avoid any potential issues with non-standard log records if record.name != "uvicorn.access": return True # it's nearly impossible for this to not be a list/tuple, but we check # just in case to avoid any potential issues if not isinstance(record.args, (list, tuple)): return True try: path = record.args[2] # /healthz/ or /readiness/ etc. if not isinstance(path, str): # ditto here. it's virtually inconceivable that this could be # something other than a string, but we check just in case return True path = path.strip("/").lower() # normalized path except (IndexError, TypeError): return True return path not in self.health_check_urls
[docs] class AccessLogQueryFilter(logging.Filter): """ Logging filter to mask sensitive query parameters in uvicorn's access log. Uvicorn logs every request's path with its query string. Clients send a chat's session key there, e.g. ``POST /api/v1/llm-clients/<id>/config/?session_key=<key>``, and anyone holding the key could read and continue that chat. This filter replaces the path argument of each ``uvicorn.access`` record with :func:`~smarter.common.utils.mask_url_query` of it, so the log shows ``?session_key=****325c05``. It never suppresses a record. Records of other loggers, records without a query, and records whose path can't be read are emitted unchanged. Attach it to the ``uvicorn.access`` logger, not to a handler, so that it masks the record before any handler sees it: **Example:** To use this filter in a Django logging configuration:: LOGGING = { ... 'filters': { 'access_log_query': { '()': 'smarter.lib.logging.filters.AccessLogQueryFilter', }, }, 'loggers': { 'uvicorn.access': { 'filters': ['access_log_query'], }, }, ... } """ path_index = 2 """The position of the path in a uvicorn access log record's arguments, see :class:`HealthCheckFilter`."""
[docs] def filter(self, record: logging.LogRecord) -> bool: """ Mask the sensitive query parameters in a uvicorn access log record's path. **Example:** >>> f = AccessLogQueryFilter() >>> args = ("127.0.0.1:1", "POST", "/config/?session_key=77846410f51045319bd666642e325c05", "1.1", 200) >>> record = logging.makeLogRecord({"name": "uvicorn.access", "msg": '%s - "%s %s HTTP/%s" %d', "args": args}) >>> f.filter(record) True >>> record.args[2] '/config/?session_key=****325c05' :param record: The log record to be filtered. Its ``args`` are replaced when its path changes. :returns: True, always: the record is emitted, masked. """ if record.name != "uvicorn.access": return True if not isinstance(record.args, tuple): return True if len(record.args) <= self.path_index: return True path = record.args[self.path_index] if not isinstance(path, str): return True masked_path = mask_url_query(path) if masked_path == path: return True args = list(record.args) args[self.path_index] = masked_path record.args = tuple(args) return True
[docs] class AsyncioShieldedCancelFilter(logging.Filter): """ Logging filter to suppress asyncio's ``CancelledError exception in shielded future`` error. Smarter runs under uvicorn (ASGI), and most of its middleware is synchronous, so asgiref runs each request's synchronous code in a worker thread, inside :func:`asyncio.shield`. When a client disconnects before the response is sent, Django's ASGI handler cancels the request's task. The shielded work in the thread then ends with :class:`asyncio.CancelledError`, and asyncio's default exception handler logs it at ERROR level with a long traceback through the whole middleware chain, for example:: CancelledError exception in shielded future future: <Future finished exception=CancelledError()> Some Python builds report the same event differently: the shielded future's exception is never retrieved, so it is logged when the future is garbage collected instead:: Future exception was never retrieved future: <Future finished exception=CancelledError()> Nothing failed: nobody is waiting for the response anymore. This filter drops those records, and only those, from the ``asyncio`` logger: the shielded-future message, and the never-retrieved message when its exception is a :class:`asyncio.CancelledError`. Every other asyncio error is still emitted. **Example:** To use this filter in a Django logging configuration:: LOGGING = { ... 'filters': { 'asyncio_shielded_cancel': { '()': 'smarter.lib.logging.filters.AsyncioShieldedCancelFilter', }, }, 'loggers': { 'asyncio': { 'filters': ['asyncio_shielded_cancel'], }, }, ... } """ message_prefix = "CancelledError exception in shielded future" """The beginning of the message that asyncio logs, see :func:`asyncio.shield`.""" never_retrieved_prefix = "Future exception was never retrieved" """The beginning of the message that asyncio logs when a failed future is garbage collected."""
[docs] def filter(self, record: logging.LogRecord) -> bool: """ Determine whether a log record should be emitted. **Example:** >>> f = AsyncioShieldedCancelFilter() >>> f.filter(logging.makeLogRecord({"name": "asyncio", "msg": "CancelledError exception in shielded future"})) False >>> f.filter(logging.makeLogRecord({"name": "asyncio", "msg": "Task exception was never retrieved"})) True :param record: The log record to be filtered. :returns: False if the record is asyncio's shielded-future or never-retrieved ``CancelledError`` and should be suppressed; True otherwise (the log record will be emitted). """ if record.name != "asyncio": return True try: message = record.getMessage() except (TypeError, ValueError): return True if message.startswith(self.message_prefix): return False if message.startswith(self.never_retrieved_prefix) and record.exc_info: return not isinstance(record.exc_info[1], asyncio.CancelledError) return True