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: |
required |
level
|
int
|
Initial log level. Defaults to :data: |
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.
|
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 |
None
|
log_return_value
|
bool
|
When |
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. |
required |
message
|
str | None
|
Optional label prepended to the output. Defaults to
|
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 |
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: |
None
|
enable_color
|
bool | None
|
Enable the Rich console handler. Defaults to TTY detection.
|
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 |
None
|
configure_root
|
bool | None
|
Configure the root logger ( |
None
|
update_loggers
|
dict[str, int] | None
|
Map of |
None
|
enable_otel_correlation
|
bool | None
|
Inject OTel trace/span IDs. Default |
None
|
otel_optional
|
bool | None
|
Suppress |
None
|
level_styles
|
dict[str, str] | None
|
Per-level Rich style overrides (e.g.
|
None
|
rich_tracebacks
|
bool | None
|
Install |
None
|
redact
|
bool | None
|
Replace secrets in messages, arguments and extra fields with
:data: |
None
|
force_reconfigure
|
bool
|
Re-run configuration even if already configured.
Default |
False
|
Returns:
| Type | Description |
|---|---|
AppLogger
|
The root :class: |
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. |
required |
message
|
str | None
|
Optional label prepended to the output. Defaults to
|
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: |
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
|
required |
environment
|
str | None
|
Deployment environment string (e.g. |
None
|
inject_otel_defaults
|
bool
|
When |
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 |
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: |
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 |