Smarter 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 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 uvicorn’s access log records of health check requests. It can be used in Django or standard Python logging configurations.

  • 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.

  • 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.

class smarter.lib.logging.filters.AccessLogQueryFilter(name='')[source]

Bases: 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 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'],
        },
    },
    ...
}
__init__(name='')

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)[source]

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'
Parameters:

record (LogRecord) – The log record to be filtered. Its args are replaced when its path changes.

Return type:

bool

Returns:

True, always: the record is emitted, masked.

path_index = 2

The position of the path in a uvicorn access log record’s arguments, see HealthCheckFilter.

class smarter.lib.logging.filters.AsyncioShieldedCancelFilter(name='')[source]

Bases: 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 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 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 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'],
        },
    },
    ...
}
__init__(name='')

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

filter(record)[source]

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
Parameters:

record (LogRecord) – The log record to be filtered.

Return type:

bool

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).

message_prefix = 'CancelledError exception in shielded future'

The beginning of the message that asyncio logs, see 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.

class smarter.lib.logging.filters.HealthCheckFilter(name='')[source]

Bases: 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 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 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.

__init__(name='')

Initialize a filter.

Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event.

property amnesty_urls: list[str]

Returns a list of URLs that are exempt from certain checks.

Returns:

List of URL path strings that are exempt.

Return type:

list[str]

bool_environment_variable(var_name, default=False)

Retrieves a boolean value from an environment variable.

This method checks the specified environment variable and returns its value as a boolean. It recognizes common truthy values such as “true”, “1”, “yes”, and “on”. If the variable is not set or cannot be interpreted as a boolean, it returns the provided default value.

Parameters:
  • var_name (str) – The name of the environment variable to check.

  • default (bool) – The default boolean value to return if the environment variable is not set or invalid.

Returns:

The boolean value of the environment variable or the default.

Return type:

bool

data_to_dict(data)

Converts data to a dictionary, handling different types of input.

This method accepts either a dictionary or a string. If a string is provided, it will attempt to parse it as JSON first, and if that fails, as YAML. If parsing fails or the data type is unsupported, a SmarterValueError is raised.

Parameters:

data (dict[str, Any] | str) – The data to convert, either a dict or a JSON/YAML string.

Returns:

The data as a dictionary.

Return type:

dict[str, Any]

Raises:

SmarterValueError – If the data cannot be converted to a dictionary.

deserves_amnesty(slug)

Determines if a given URL deserves amnesty based on the amnesty URLs list.

This excuses certain endpoints (like health checks) from select middleware checks.

Parameters:

slug (str) – The URL path to check.

Returns:

True if the URL deserves amnesty, False otherwise.

Return type:

bool

dict_is_contained_in(dict1, dict2)

Checks if one dictionary is contained within another.

This method determines if all key-value pairs in dict1 are present in dict2.

Parameters:
  • dict1 (dict[str, Any]) – The dictionary to check for containment.

  • dict2 (dict[str, Any]) – The dictionary to check against for containment.

Returns:

True if dict1 is contained in dict2, False otherwise.

Return type:

bool

dict_is_subset(small, big)

Checks if one dictionary is a subset of another.

This method determines if all key-value pairs in the small dictionary are present in the big dictionary. It returns True if the small dictionary is a subset of the big dictionary, and False otherwise.

Parameters:
  • small (dict[str, Any]) – The dictionary to check as a subset.

  • big (dict[str, Any]) – The dictionary to check against as a superset.

Returns:

True if the small dictionary is a subset of the big dictionary, False otherwise.

Return type:

bool

filter(record)[source]

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:

(
    "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
Parameters:

record (LogRecord) – The log record to be filtered.

Return type:

bool

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).

formatted_class_name = '\x1b[1;31mHealthCheckFilter\x1b[0m'
formatted_json(json_obj)

Formats a JSON object as a pretty-printed string with ANSI color codes for logging.

Parameters:

json_obj (dict[str, Any] | list) – The JSON object (dict or list) to format.

Returns:

A string representation of the JSON object with ANSI color codes.

Return type:

str

property formatted_state_not_ready: str

Returns the not-ready state formatted for logging.

Returns:

The formatted not-ready state as a string.

Return type:

str

property formatted_state_ready: str

Returns the readiness state formatted for logging.

Returns:

The formatted readiness state as a string.

Return type:

str

formatted_text(text, color_code='\x1b[1;31m')

Formats text with ANSI color codes for logging.

Parameters:
  • text (str) – The text to format.

  • color_code (str) – The ANSI color code to apply.

Returns:

The formatted text with ANSI color codes.

Return type:

str

formatted_text_blue(text)

Formats text in bold dark blue for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bold dark blue.

Return type:

str

formatted_text_green(text)

Formats text in bright green for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in bright green.

Return type:

str

formatted_text_red(text)

Formats text in dark red for logging.

Parameters:

text (str) – The text to format.

Returns:

The formatted text in dark red.

Return type:

str

generate_fernet_encryption_key()

Generates a Fernet encryption key.

This method creates a new Fernet encryption key, which can be used for secure encryption and decryption of data. The generated key is returned as a URL-safe base64-encoded string.

Returns:

A new Fernet encryption key.

Return type:

str

get_readonly_csv_file(file_path)

Reads a CSV file and returns its contents as a list of dictionaries, one per row.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the CSV file to read.

Returns:

The rows of the CSV file, one dictionary per row, keyed by the column headers.

Return type:

list[dict]

get_readonly_yaml_file(file_path)

Reads a YAML file and returns its contents as a dictionary.

The file is opened read-only, so reading it never modifies it.

Parameters:

file_path (str) – The path to the YAML file to read.

Returns:

The contents of the YAML file, parsed into a dictionary.

Return type:

dict

property health_check_urls: list[str]

Returns a list of URL paths that are considered health check endpoints.

Returns:

List of health check URL path strings.

Return type:

list[str]

mask_string(string='', mask_char='*', mask_length=4, string_length=8)

Masks a string for secure logging.

This utility function masks all but the last unmasked_chars characters of the input string, replacing them with asterisks. It is useful for logging sensitive information like API keys or passwords.

Parameters:
  • string (str | None) – The string to be masked.

  • mask_char (str) – The character used for masking.

  • mask_length (int) – The number of characters to mask.

  • string_length (int) – The length of the string to consider for masking.

Returns:

The masked string.

Return type:

str

property ready: bool

Indicates whether the object is ready for use.

This is a placeholder that should be overridden in subclasses.

Returns:

True if ready, False otherwise.

Return type:

bool

recursive_sort_dict(data)

Recursively sorts a dictionary by its keys.

This method takes a dictionary and returns a new dictionary with all keys sorted in ascending order. If any values are also dictionaries, they will be sorted recursively as well.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with all keys sorted.

Return type:

dict[str, Any]

rfc1034_compliant_str(name)

Converts a string to an RFC 1034 compliant format.

This method takes a string and converts it to a format that complies with RFC 1034, which is commonly used for domain names. It replaces invalid characters with hyphens and ensures the resulting string is lowercase.

Parameters:

name (str) – The string to convert to RFC 1034 compliant format.

Returns:

The converted string in RFC 1034 compliant format.

Return type:

str

rfc1034_compliant_to_snake(name)

Converts an RFC 1034 compliant string to snake_case.

This method takes a string in RFC 1034 compliant format and converts it to snake_case. It replaces hyphens with underscores and ensures the resulting string is lowercase.

Parameters:

name (str) – The RFC 1034 compliant string to convert.

Returns:

The converted string in snake_case.

Return type:

str

smarter_build_absolute_uri(request)

Attempts to get the absolute URI from a request object.

This utility function tries to retrieve the request URL from any valid child class of django.http.HttpRequest. It is especially useful in unit tests or scenarios where the request object may not implement build_absolute_uri().

Parameters:

request (HttpRequest) – The request object.

Returns:

The absolute request URL.

Return type:

str | None

Raises:

SmarterValueError – If the URI cannot be built from the request.

sorted_dict(data)

Returns a new dictionary with keys sorted.

Parameters:

data (dict[str, Any]) – The dictionary to sort.

Returns:

A new dictionary with sorted keys.

Return type:

dict[str, Any]

to_camel_case(data, convert_values=False)

Converts a snake_case string to camelCase.

This method takes a string in snake_case format and converts it to camelCase. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The snake_case string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in camelCase.

Return type:

ConvertibleCaseT

to_snake_case(data, convert_values=False)

Converts a camelCase or PascalCase string to snake_case.

This method takes a string in camelCase or PascalCase format and converts it to snake_case. It is useful for standardizing naming conventions across different formats.

Parameters:
  • data (ConvertibleCaseT) – The camelCase or PascalCase string to convert.

  • convert_values (bool) – Whether to convert the values of dictionaries and lists recursively.

Returns:

The converted string in snake_case.

Return type:

ConvertibleCaseT

property unformatted_class_name: str

Returns the raw class name without formatting.

Returns:

The unformatted class name as a string.

Return type:

str

This is useful for logging or serialization where the plain class name is needed.