Skip to content

logger

Here's the reference for the logging utilities.

You can import them directly from fastapi_toolsets.logger:

from fastapi_toolsets.logger import (
    ACCESS_FIELDS,
    ACCESS_LOGGER,
    DEFAULT_PROPAGATE_LOGGERS,
    DEFAULT_QUIET_LOGGERS,
    ConsoleFormatter,
    ContextFilter,
    JsonFormatter,
    LoggingConfig,
    LogLevel,
    LogStyle,
    RequestLoggingMiddleware,
    SharedRotatingFileHandler,
    bind_log_context,
    configure_logging,
    current_log_context,
    get_logger,
    init_logging,
    log_context,
)

fastapi_toolsets.logger.init_logging(app, config=None, *, access_log=None, request_id_header='X-Request-ID', trust_incoming_id=False, client_ip=None, exclude=None)

Configure logging and add RequestLoggingMiddleware to an app.

Call it after adding your other middleware so it wraps them.

Parameters:

Name Type Description Default
app FastAPI

The FastAPI application.

required
config LoggingConfig | None

Passed to configure_logging.

None
access_log bool | None

Log one line per request in place of uvicorn's access log. None uses config.access_log, or True when that is unset.

None
request_id_header str | None

Response header carrying the request id.

'X-Request-ID'
trust_incoming_id bool

Reuse a valid request id sent by the client.

False
client_ip Callable[[Scope], str | None] | None

Returns the client IP for a scope.

None
exclude Callable[[Scope], bool] | None

Returns True for requests to leave untouched.

None

Returns:

Type Description
FastAPI

The same FastAPI instance (for chaining).

Example
from fastapi import FastAPI
from fastapi_toolsets.logger import LoggingConfig, init_logging

app = FastAPI()
init_logging(app, LoggingConfig.from_env())

fastapi_toolsets.logger.configure_logging(config=None, **overrides)

Configure the root logger, third-party loggers, and the OpenTelemetry bridge.

Calling it again replaces the handlers it installed.

Parameters:

Name Type Description Default
config LoggingConfig | LogLevel | int | None

Settings to apply, or a level applied to LoggingConfig(). Defaults to LoggingConfig().

None
**overrides Any

Fields replacing those of config.

{}

Returns:

Type Description
Logger

The root logger.

Raises:

Type Description
ValueError

If style is unknown.

ImportError

If otel is True and the otel extra is missing.

Example
from fastapi_toolsets.logger import LoggingConfig, configure_logging

configure_logging(LoggingConfig.from_env(), level="DEBUG")

fastapi_toolsets.logger.LoggingConfig dataclass

Settings for configure_logging.

Parameters:

Name Type Description Default
level LogLevel | int

Root log level.

'INFO'
style LogStyle

"console", "json", or "auto" for console on a terminal and JSON otherwise.

'auto'
stream Literal['stderr', 'stdout']

Stream the console or JSON handler writes to.

'stderr'
colors bool | None

Color console output. None enables it on a terminal.

None
datefmt str

strftime format of console timestamps, followed by milliseconds. Use "%Y-%m-%d %H:%M:%S" to show the date.

'%H:%M:%S'
request_id_length int

Characters of the request id and other ids shown on the console.

8
service str | None

service key of JSON records. Defaults to OTEL_SERVICE_NAME.

None
file str | PathLike[str] | None

Log file written as well, shared by every process of the application and rotated by size. Console lines in it carry the date and no colors.

None
file_max_bytes int

Size after which the file is rotated. 0 leaves rotation to an external tool such as logrotate.

50000000
file_backups int

Rotated files kept.

5
propagate Sequence[str]

Loggers whose own handlers are removed so their records reach the root handlers.

DEFAULT_PROPAGATE_LOGGERS
access_log bool | None

Cap uvicorn.access at WARNING because RequestLoggingMiddleware logs each request instead. None means off for configure_logging and on for init_logging.

None
levels Mapping[str, LogLevel | int]

Per-logger levels, applied last.

dict()
quiet Sequence[str]

Loggers capped at WARNING.

DEFAULT_QUIET_LOGGERS
sql_echo bool

Log SQLAlchemy statements at INFO.

False
otel bool | Literal['auto']

Forward records to OpenTelemetry logs. "auto" does so when the otel extra is installed.

'auto'
otel_logger_provider Any

Provider to forward to. None uses the global one.

None

from_env(prefix='LOG_', environ=None, **defaults) classmethod

Build a config from environment variables.

Reads LEVEL, STYLE, STREAM, COLORS, SERVICE, FILE, FILE_MAX_BYTES, FILE_BACKUPS, SQL_ECHO and OTEL under prefix.

Parameters:

Name Type Description Default
prefix str

Prefix of the variable names.

'LOG_'
environ Mapping[str, str] | None

Mapping to read instead of os.environ.

None
**defaults Any

Values used when a variable is unset.

{}

Returns:

Type Description
LoggingConfig

The config built from the variables and defaults.

Raises:

Type Description
ValueError

If a variable cannot be parsed.

fastapi_toolsets.logger.RequestLoggingMiddleware

Bind a request id and client IP to every record, then log one access line.

The access line is logged at ERROR for a 5xx status or an unhandled exception, whose traceback it then carries, and at INFO otherwise.

Parameters:

Name Type Description Default
app ASGIApp

The ASGI application to wrap.

required
request_id_header str | None

Response header carrying the request id. None to omit it.

'X-Request-ID'
trust_incoming_id bool

Reuse a valid id sent by the client in that header, for instance one set by a reverse proxy.

False
client_ip Callable[[Scope], str | None] | None

Returns the client IP for a scope. Defaults to the socket peer, which uvicorn's --proxy-headers sets behind a proxy.

None
exclude Callable[[Scope], bool] | None

Returns True for requests to leave untouched, with the same signature as FastAPI's telemetry["exclude"].

None
access_log bool

Log one line per request to ACCESS_LOGGER.

True

fastapi_toolsets.logger.bind_log_context(**values)

Add fields to every record logged in the current scope.

Inside a request handled by RequestLoggingMiddleware, the fields stay bound until the request ends.

Concurrent tasks of a request share these fields: run each in log_context to keep its own.

Parameters:

Name Type Description Default
**values Any

Fields to bind. A None value is not emitted.

{}

fastapi_toolsets.logger.log_context(**values)

Bind fields for the duration of the block, then restore the previous set.

Parameters:

Name Type Description Default
**values Any

Fields to bind. A None value is not emitted.

{}

fastapi_toolsets.logger.current_log_context()

Return a copy of the fields bound to the current context.

fastapi_toolsets.logger.ContextFilter

Bases: Filter

Attach the fields bound with the context helpers to every record.

fastapi_toolsets.logger.JsonFormatter

Bases: Formatter

Render a record as a single JSON object.

Parameters:

Name Type Description Default
service str | None

Value of the service key. Omitted when None.

None

fastapi_toolsets.logger.ConsoleFormatter

Bases: Formatter

Render a record as one short line for reading in a terminal.

Within a request, the fields bound for the whole request are replaced by a short request id tag and shown only on the access line.

Parameters:

Name Type Description Default
colors bool

Color the level and dim the logger name and fields.

False
datefmt str

strftime format of the timestamp, followed by milliseconds.

'%H:%M:%S'
request_id_length int

Characters of the request id and other ids shown.

8
hidden_fields Mapping[str, Collection[str]] | None

Fields left out per logger name. Defaults to the access line fields its message already shows.

None
logger_names Mapping[str, str] | None

Names displayed in place of logger names. Defaults to access for the access logger.

None

fastapi_toolsets.logger.SharedRotatingFileHandler

Bases: RotatingFileHandler

A RotatingFileHandler that several processes can write to at once.

Each record is written under a lock on a .lock file next to the log, so uvicorn workers share one file and one of them rotates it. A process whose file was renamed, by a sibling or by logrotate, reopens it before writing. With maxBytes=0 the handler never rotates and only follows external rotation. A process forked after the handler was built reopens the lock and the file, so it is excluded from its parent too.

On platforms without fcntl the processes do not coordinate.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path of the log file.

required
maxBytes int

Size after which the file is rotated. 0 disables rotation.

0
backupCount int

Rotated files kept. 0 disables rotation.

0
**kwargs Any

Passed to RotatingFileHandler.

{}

fastapi_toolsets.logger.get_logger(name=_SENTINEL)

Return a logger with the given name.

When called without arguments, the caller's __name__ is used, so get_logger() in a module is equivalent to logging.getLogger(__name__). Pass None to get the root logger.

Parameters:

Name Type Description Default
name str | None

Logger name. Defaults to the caller's __name__.

_SENTINEL

Returns:

Type Description
Logger

A Logger instance.

Example
from fastapi_toolsets.logger import get_logger

logger = get_logger()          # uses caller's __name__
logger = get_logger("myapp")   # explicit name
logger = get_logger(None)      # root logger