Skip to content

Logger

rn_forge.commons.logging.logger

Configured application logging with custom levels and record enrichment.

:class:AppLogger uses {}-style messages and idempotent dictConfig initialization. Console output uses Rich when color is enabled on a TTY; file output retains the full plain-text format. :class:EnrichFilter adds caller, service, environment, and optional OpenTelemetry fields; :class:RedactFilter replaces secrets in messages, arguments and extra fields.

AppLogger(name, level=logging.NOTSET)

Bases: VerboseLoggerBase

Custom logger with TRACE level, runtime level switching, and audit decorators.

Extends :class:verboselogs.VerboseLogger which already provides verbose, notice, spam, and success levels.

Call :meth:initialize once at process start-up (e.g. in main(), wsgi.py, or AppConfig.ready()).

Typical usage::

logger = AppLogger.initialize(root_logger_name="billing", level=AppLogger.INFO)
logger.info("service started | version={}", "1.2.3")

app_logger = AppLogger.get_logger(__name__)
app_logger.debug("request_id={}", request_id)

Initialize :class:AppLogger.

Reads the AUDIT_LOG_LEVEL (default "SPAM") and AUDIT_FIELD_SEPARATOR (default " | ") environment variables to configure audit decorator behaviour.

Parameters:

Name Type Description Default
name str

Logger name passed to the underlying :class:verboselogs.VerboseLogger.

required
level int

Initial log level. Defaults to :data:logging.NOTSET.

NOTSET

audit_class(*, exclude=None, include=None, include_inherited=False, level=None, log_return_value=False)

Class decorator that applies :meth:audit_method to every public method.

Skips private (_-prefixed) and dunder (__-prefixed) methods. Set include_inherited=True to wrap public methods inherited from base classes as well.

Example::

logger = AppLogger.get_logger(__name__)

@logger.audit_class(exclude=["token"])
class Client:
    def fetch(self, token: str, resource_id: str) -> dict[str, Any]:
        ...

audit_method(*, exclude=None, include=None, level=None, log_return_value=False)

Decorator that logs method entry (with args) and exit (with timing).

Parameters:

Name Type Description Default
exclude list[str] | None

Parameter names to omit from the entry log. self and cls are always excluded automatically.

None
include list[str] | None

When provided, only these parameter names are logged.

None
level int | None

Logging level for audit messages. Defaults to the AUDIT_LOG_LEVEL env-var (default SPAM).

None
log_return_value bool

When True, log the return value after the call. Avoid for methods that return large objects or lazy iterables.

False

Example::

logger = AppLogger.get_logger(__name__)

@logger.audit_method(exclude=["password"])
def authenticate(user: str, password: str) -> bool:
    ...

critical(msg, *args, **kwargs)

Log a message at the CRITICAL level.

debug(msg, *args, **kwargs)

Log a message at the DEBUG level.

debug_variables(var_names, message=None)

Log one or more variables by name at DEBUG level.

Variable values are resolved from the caller's frame at call time.

Parameters:

Name Type Description Default
var_names str

Comma-separated string of variable names to resolve, e.g. "request, user_id".

required
message str | None

Optional label prepended to the output. Defaults to "Variables".

None

Example::

logger.debug_variables("request_id, payload.order_id")

error(msg, *args, **kwargs)

Log a message at the ERROR level.

exception(msg, *args, **kwargs)

Log a message with exception context at the ERROR level.

fatal(msg, *args, **kwargs)

Log a message at the FATAL level.

get_logger(name) classmethod

Return an :class:AppLogger registered under name.

Registers :class:AppLogger as the logger class for new loggers and preserves the installed record factory. Existing loggers are returned unchanged.

info(msg, *args, **kwargs)

Log a message at the INFO level.

initialize(*, root_logger_name, level=None, file=None, fmt=None, enable_color=None, isatty=None, use_json=None, configure_root=None, update_loggers=None, enable_otel_correlation=None, otel_optional=None, level_styles=None, rich_tracebacks=None, redact=None, force_reconfigure=False) staticmethod

Idempotently configure logging in a thread-safe manner.

Uses logging.config.dictConfig and preserves the installed record factory. Subsequent calls return the existing logger unless force_reconfigure is True.

All arguments are keyword-only. Pass only what you want to override; :meth:LoggingConfig.build supplies the defaults for everything omitted or left as None.

Parameters:

Name Type Description Default
root_logger_name str

Name for the root application logger (required).

required
level int | None

Log level. Defaults to VERBOSE (or DEFAULT_LOG_LEVEL env-var).

None
file str | None

Path to a log file. Optional suffix; datestamp appended when omitted.

None
fmt str | None

Log format string. Defaults to :attr:AppLogger.DEFAULT_FORMAT.

None
enable_color bool | None

Enable the Rich console handler. Defaults to TTY detection. use_json=True always wins over this, even when set.

None
isatty bool | None

Override TTY detection used by enable_color.

None
use_json bool | None

Emit JSON log records instead of plain text. Default False.

None
configure_root bool | None

Configure the root logger (True) or only the named logger (False, useful inside libraries). Default True.

None
update_loggers dict[str, int] | None

Map of {logger_name: level} overrides for third-party loggers (e.g. {"django": logging.WARNING}).

None
enable_otel_correlation bool | None

Inject OTel trace/span IDs. Default False.

None
otel_optional bool | None

Suppress ImportError when opentelemetry is absent. Default True.

None
level_styles dict[str, str] | None

Per-level Rich style overrides (e.g. {"critical": "bold white on red"}), merged over the built-in theme that styles verboselogs' custom levels. Only applies to the RichHandler console path.

None
rich_tracebacks bool | None

Install rich.traceback for the RichHandler console path, without local variables. Default True.

None
redact bool | None

Replace secrets in messages, arguments and extra fields with :data:~rn_forge.commons.logging.redaction.REDACTED before any handler formats them. Default True. Exception tracebacks are not redacted.

None
force_reconfigure bool

Re-run configuration even if already configured. Default False.

False

Returns:

Type Description
AppLogger

The root :class:AppLogger named root_logger_name.

Example::

logger = AppLogger.initialize(
    root_logger_name="orders",
    level=AppLogger.DEBUG,
    file="logs/orders",
    enable_color=True,
)

makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

Create a record through the installed factory with brace message support.

notice(msg, *args, **kwargs)

Log a message at the NOTICE level.

restore_level()

Revert this logger and all root handlers to the level set at construction.

Does nothing when the current level already matches the initial level.

spam(msg, *args, **kwargs)

Log a message at the SPAM level.

success(msg, *args, **kwargs)

Log a message at the SUCCESS level.

trace(msg, *args, **kwargs)

Log a message at the TRACE level.

trace_variables(var_names, message=None)

Log one or more variables by name at TRACE level.

Variable values are resolved from the caller's frame at call time.

Parameters:

Name Type Description Default
var_names str

Comma-separated string of variable names to resolve, e.g. "payload, headers".

required
message str | None

Optional label prepended to the output. Defaults to "Variables".

None

Example::

logger.trace_variables("response.status_code, response.headers")

update_level(level)

Temporarily change this logger and all root handlers to level.

Does nothing when level equals the logger's initial level.

Parameters:

Name Type Description Default
level int

The new log level (e.g. :data:logging.DEBUG).

required

verbose(msg, *args, **kwargs)

Log a message at the VERBOSE level.

warning(msg, *args, **kwargs)

Log a message at the WARNING level.

BraceLogRecord

Bases: LogRecord

LogRecord supporting % formatting when present, otherwise str.format.

A single dict argument is formatted as one positional argument. Brace formatting errors return the message followed by the argument repr.

EnrichFilter(service_name, environment=None, *, inject_otel_defaults=False)

Bases: Filter

Injects consistent fields into every log record.

Fields always added:

  • caller: <logger name>.<funcName>
  • service, env: identity fields from constructor / env-vars

OTel placeholder fields (otelTraceID, otelSpanID, otelServiceName, otelTraceSampled) are only injected when inject_otel_defaults is True, preventing noisy trace_id=- output when OpenTelemetry is not in use.

Initialize :class:EnrichFilter.

Parameters:

Name Type Description Default
service_name str

Identifier for the running service, injected as the service field on every log record.

required
environment str | None

Deployment environment string (e.g. "production"). When None, resolved from the environment variables ENVIRONMENT, DJANGO_ENV, or APP_ENV in that order, falling back to "unknown".

None
inject_otel_defaults bool

When True, inject otelTraceID, otelSpanID, otelServiceName, and otelTraceSampled placeholder fields on records that do not already have them. Defaults to False.

False

filter(record)

Enrich record with service, env, caller, and optional OTel fields.

Always returns True (the record is never suppressed).

Parameters:

Name Type Description Default
record LogRecord

The log record to enrich in-place.

required

Returns:

Type Description
bool

Always True.

LoggingConfig(root_logger_name, level, file, fmt, rich_fmt, enable_color, isatty, use_json, configure_root, update_loggers, enable_otel_correlation, otel_optional, level_styles, rich_tracebacks, redact) dataclass

Resolved logging configuration produced by :meth:build.

Do not construct directly — use :meth:build so that all defaults are applied. All fields are guaranteed to have a value after build(); file is the only field that can be None (meaning no file handler).

level_styles maps a level name (e.g. "critical") to a Rich style string, merged over the built-in theme (:data:_RICH_LEVEL_STYLES) that styles the verboselogs custom levels. Only used when the RichHandler console path is selected.

build(**overrides) classmethod

Return a fully-resolved config by merging overrides onto :meth:defaults.

None values in overrides are treated as "not provided" and fall back to the default. Pass False or 0 to explicitly override a truthy default.

fmt is derived from enable_otel_correlation when not explicitly provided: _OTEL_FORMAT is used when OTel correlation is enabled, _DEFAULT_FORMAT otherwise. rich_fmt (used only by the RichHandler console path) is derived the same way from _RICH_FORMAT/_RICH_OTEL_FORMAT. An explicit fmt= override wins for every handler type, including Rich.

defaults() classmethod

Return all concrete defaults as a plain dict.

This is the single source of truth for every default value. Dynamic defaults (TTY detection, env-var level) are resolved here at call time, not at import time.

RedactFilter(policy=None)

Bases: Filter

Redacts secrets from every log record.

Redacts record.msg when it is a string, record.args (tuple or mapping, with non-string arguments kept as they are) and every extra field, using :func:~rn_forge.commons.logging.redaction.redact. It assigns new objects to the record and never mutates what the caller passed. Running it more than once on a record changes nothing further.

Initialize :class:RedactFilter.

Parameters:

Name Type Description Default
policy RedactionPolicy | None

What to redact. Defaults to :meth:RedactionPolicy.default.

None

filter(record)

Redact record in place.

If redaction fails, the message is replaced by the redaction marker rather than risk emitting a secret.

Parameters:

Name Type Description Default
record LogRecord

The log record to redact.

required

Returns:

Type Description
bool

Always True.