Source code for smarter.lib.logging.filters

"""
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
-------
HealthCheckFilter
    A logging filter that excludes log records related to health check URLs. It can be used in Django or
    standard Python logging configurations to automatically filter out health check requests from logs.

Examples
--------
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'],
            },
        },
        ...
    }

Any log entries containing a health check URL substring (as defined in ``health_check_urls``)
will be suppressed by this filter.
"""

from smarter.common.mixins import SmarterHelperMixin
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 works by inspecting each log record's message and checking if it contains any substring from the ``health_check_urls`` attribute, which should be a list of health check URL patterns. If a match is found, the log record is suppressed (not emitted). Inherits from :class:`SmarterHelperMixin` to provide access to shared configuration and helpers. Attributes ---------- health_check_urls : list of str List of URL substrings that identify health check endpoints. Log records containing any of these substrings in their message will be filtered out (not logged). Examples -------- 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 log entries for any request matching the URLs in ``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 URLs is provided by the ``health_check_urls`` attribute, which should be a list of string patterns (e.g., "/healthz/", "/readiness/"). Both the log path and the health check URLs are normalized by stripping leading/trailing slashes and lowercasing before comparison, so that variants like "/healthz", "/healthz/", or "healthz" all match. 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 ) Parameters ---------- record : logging.LogRecord The log record to be filtered. Returns ------- bool False if the log record path matches a health check URL and should be suppressed; True otherwise (the log record will be emitted). Examples -------- >>> 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 = ["/healthz/", "/readiness/"] >>> filter.filter(DummyRecord()) False >>> DummyRecord.args = ("127.0.0.1:12345", "GET", "/api/v1/resource/", "1.1", 200) >>> filter.filter(DummyRecord()) True """ # 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