Skip to main content

FastAPI logging bootstrap: dev-friendly console, production structlog JSON

Project description

fastapi-logkit

FastAPI logging bootstrap: readable console logs in development, structured structlog JSON to stdout in production-minded environments.

  • Prefer turning off Uvicorn/Gunicorn access logs and emitting HTTP access as structured middleware logs instead.
  • The global exception handler logs unhandled request errors; process-level logs are normalized via Uvicorn/Gunicorn logger wiring.

Usage

fastapi_logkit does not read OS environment variables. Read deploy env, log level, etc. in your app and pass values into helpers.

import os
from fastapi import FastAPI
from fastapi_logkit import setup_logging
from fastapi_logkit.fastapi import install_logkit

def app_env() -> str:
    return (os.getenv("APP_ENV") or os.getenv("ENVIRONMENT") or "development").strip()

cfg = setup_logging(
    env=app_env(),
    level=os.getenv("LOG_LEVEL", "INFO").strip().upper(),
)

app = FastAPI()
install_logkit(app, config=cfg)
  • With install_logkit(..., config=cfg), the exception handler mirrors cfg.json_logs (structured JSON vs app.error text).
  • If access_log is omitted, it defaults from is_production_environment(cfg.env).

When running Uvicorn, pass the same env semantics into get_uvicorn_log_config_for_run(env=..., silence_uvicorn=...) as for setup_logging. Example:

from fastapi_logkit.env_util import is_json_logging_environment
from fastapi_logkit.integrations.uvicorn import get_uvicorn_log_config_for_run

e = app_env()
uvicorn.run(
    "main:app",
    log_config=get_uvicorn_log_config_for_run(
        env=e, silence_uvicorn=is_json_logging_environment(e)
    ),
)

Production-style run: uvicorn main:app --host 0.0.0.0 --port 8000 --no-access-log


Behaviour summary (arguments / helpers)

API / helper Description
setup_logging(env=..., level="INFO", json_logs=None, ...) Omit json_logs to derive it from is_json_logging_environment(env) (production / prod / staging → JSON pipeline).
is_json_logging_environment(env) Whether env is treated as a JSON-logging env; string only (does not touch os).
is_production_environment(env) True only for production / prod — default access middleware install in install_logkit.
resolve_env_name(env) If env is None, returns "development" (no env var lookup).
configure_logging(...) Alias of setup_logging.

Body redaction, proxy IP trust, and which access lines are emitted are configured via AccessLogOptions + install_logkit(..., access_log_options=...).

HTTP access line threshold

Each access line is classified with a stdlib severity: 2xx/3xx → INFO, 4xx → WARNING, 5xx → ERROR. A line is emitted only if that severity is the configured minimum.

  • By default, install_logkit(..., config=cfg) sets the access minimum from cfg.level (same string as setup_logging(..., level=...)). For example, level="WARNING" suppresses successful 2xx/3xx access lines but still records 4xx and 5xx.
  • Set AccessLogOptions(access_min_level=logging.WARNING) (or another numeric level) to override the threshold without changing the global structlog floor.

JSON line fields (JSON mode)

Each stdout line is produced by structlog.processors.JSONRenderer(), with fields merged as follows:

Category Fields
Common (processors) env — name passed into setup_logging. logLevel — numeric Pino-like level (e.g. info=30). The event key is stripped right before rendering.
Request context (RequestContextMiddleware) request_id, method, path merged from structlog contextvars.
Access log (AccessLogMiddleware) statusCode, userAgent, clientIP, originIP, dateTime (ms timestamp), endPoint, pathParams, method, traceBack when present. For 4xx/5xx with body logging enabled, requestBody.
JSON unhandled_exception_handler without access middleware on the stack traceBack, endPoint, method, statusCode (500). May skip when access middleware already logged the same failure.
App kwargs Any keys passed to logger.info("name", **fields) are included verbatim.

See the fastapi_logkit/ source for processors and middleware details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_logkit-0.1.0.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_logkit-0.1.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_logkit-0.1.0.tar.gz.

File metadata

  • Download URL: fastapi_logkit-0.1.0.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for fastapi_logkit-0.1.0.tar.gz
Algorithm Hash digest
SHA256 3978442ae3edb37bf5699f726d5750a267978875ca99f8b76c001495aaa34b22
MD5 0619dd9d1cadce0d5990122c9486ff46
BLAKE2b-256 3892a2c61a917461de87e83bdc6859ecb471ad17c9f7dedffff3cbd14083dd6d

See more details on using hashes here.

File details

Details for the file fastapi_logkit-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_logkit-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for fastapi_logkit-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 505dd6366e9d603246a1bea161ef08368cde11123d8c11f6abf07ac094c05462
MD5 55ce42c5bdcf20988b83b233b0be2b88
BLAKE2b-256 e60acefdbce1a63344c4736b3fd448cd95f746a2c7448a0afd8570a754539075

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page