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 |
None
|
access_log
|
bool | None
|
Log one line per request in place of uvicorn's access log.
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
FastAPI
|
The same FastAPI instance (for chaining). |
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 |
None
|
**overrides
|
Any
|
Fields replacing those of |
{}
|
Returns:
| Type | Description |
|---|---|
Logger
|
The root logger. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ImportError
|
If |
fastapi_toolsets.logger.LoggingConfig
dataclass
¶
Settings for configure_logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
LogLevel | int
|
Root log level. |
'INFO'
|
style
|
LogStyle
|
|
'auto'
|
stream
|
Literal['stderr', 'stdout']
|
Stream the console or JSON handler writes to. |
'stderr'
|
colors
|
bool | None
|
Color console output. |
None
|
datefmt
|
str
|
|
'%H:%M:%S'
|
request_id_length
|
int
|
Characters of the request id and other ids shown on the console. |
8
|
service
|
str | None
|
|
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. |
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 |
None
|
levels
|
Mapping[str, LogLevel | int]
|
Per-logger levels, applied last. |
dict()
|
quiet
|
Sequence[str]
|
Loggers capped at |
DEFAULT_QUIET_LOGGERS
|
sql_echo
|
bool
|
Log SQLAlchemy statements at |
False
|
otel
|
bool | Literal['auto']
|
Forward records to OpenTelemetry logs. |
'auto'
|
otel_logger_provider
|
Any
|
Provider to forward to. |
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 |
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. |
'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 |
None
|
exclude
|
Callable[[Scope], bool] | None
|
Returns |
None
|
access_log
|
bool
|
Log one line per request to |
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 |
{}
|
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 |
{}
|
fastapi_toolsets.logger.current_log_context()
¶
Return a copy of the fields bound to the current context.
fastapi_toolsets.logger.ContextFilter
¶
fastapi_toolsets.logger.JsonFormatter
¶
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
|
|
'%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
|
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
|
backupCount
|
int
|
Rotated files kept. |
0
|
**kwargs
|
Any
|
Passed to |
{}
|
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 |
_SENTINEL
|
Returns:
| Type | Description |
|---|---|
Logger
|
A Logger instance. |