{"id":28404294,"url":"https://github.com/redb0/fastapi-logger","last_synced_at":"2026-01-16T11:26:51.141Z","repository":{"id":235454224,"uuid":"790560938","full_name":"redb0/fastapi-logger","owner":"redb0","description":"Structured logs and middleware for fastapi with sentry integration","archived":false,"fork":false,"pushed_at":"2026-01-14T13:06:19.000Z","size":371,"stargazers_count":20,"open_issues_count":2,"forks_count":8,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-01-14T17:24:33.726Z","etag":null,"topics":["fastapi","logging","python","sentry","structlog"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/redb0.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-04-23T05:28:59.000Z","updated_at":"2026-01-14T13:06:24.000Z","dependencies_parsed_at":"2024-08-18T17:07:05.271Z","dependency_job_id":"93bed76d-7a1a-4f3a-b3bd-c93c26b5594f","html_url":"https://github.com/redb0/fastapi-logger","commit_stats":null,"previous_names":["redb0/fastapi-logger"],"tags_count":20,"template":false,"template_full_name":null,"purl":"pkg:github/redb0/fastapi-logger","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redb0%2Ffastapi-logger","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redb0%2Ffastapi-logger/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redb0%2Ffastapi-logger/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redb0%2Ffastapi-logger/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/redb0","download_url":"https://codeload.github.com/redb0/fastapi-logger/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redb0%2Ffastapi-logger/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28478256,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-16T06:30:42.265Z","status":"ssl_error","status_checked_at":"2026-01-16T06:30:16.248Z","response_time":107,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","logging","python","sentry","structlog"],"created_at":"2025-06-01T19:38:27.710Z","updated_at":"2026-01-16T11:26:51.135Z","avatar_url":"https://github.com/redb0.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI structured logs\n\nProvides a wrapper over the structlog for additional\ndoping in json format, as well as output of standard\nlogs to the console, configuration via `.env` files\nvia pedantic.\n\nIn addition, middleware and a `sentry` configuration\nare available for use in FastAPI applications.\n\n## Installation\n\nYou can use `pip`:\n\n```bash\npip install fastapi-structlog\n```\n\nor `poetry`:\n\n```bash\npoetry add fastapi-structlog\n```\n\n## Using logging\n\nTo implement logging in an application, two things are necessary:\ndefine the configuration and use `setup_logger`:\n\n```python\nimport structlog\nfrom fastapi_structlog import setup_logger\n\nlog_settings = LogSettings(\n    logger='test-log-lib',\n    json_logs=False,\n    debug=True,\n    types=['console'],\n)\nsetup_logger(log_settings)\n\nlog = structlog.get_logger()\n\nlog.info('Hello, World!')\n```\n\nIn this case, the entire configuration is determined manually by\ncreating an instance of `LogSettings`.\n\nIf you want to get the configuration from the environment variables,\nthen add `LogSettings` as a nested model in your settings:\n\n```python\nclass Settings(BaseSettings):\n    model_config = SettingsConfigDict(\n        arbitrary_types_allowed=True,\n        env_ignore_empty=True,\n        env_nested_delimiter='__',\n        extra='ignore',\n    )\n    log: LogSettings\n```\n\nIn this case, the entire configuration is taken from\nthe `.env` file by means of Pedantic.\n\nTo use the library in the minimum version, see\nexample №1 (`docs_src/example_1.py`).\n\n## Logger configuration\n\nThe logger configuration is implemented using the pydantic model `LogSettings`.\nYou can easily integrate it into your application settings model.\n\nLogger configuration parameters:\n\n- Name of the logger (`LOGGER`), default `default`\n- Logging level (`LOG_LEVEL`), default `INFO`\n- Flag that activates logging in json format (`JSON_LOGS`), default `True`\n- Logging of the traceback in string form (`TRACEBACK_AS_STR`), default `True`\n- The name of the file (`FILENAME`), default `None`\n- The interval of writing to the file (`WHEN`), one of the `S`, `M`, `H`, `D`, `W`,\ndefault `D` (see [TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler))\n- The number of saved files (`BACKUP_COUNT`), default `1`\n(see [TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler))\n- Activate DEBUG mode (`DEBUG`), default `False`\n- New name for the key `event` (`EVENT_KEY`), default `message`\n(see [renaming the `event` key](https://www.structlog.org/en/stable/recipes.html#renaming-the-event-key))\n- Enable logging (`ENABLE`), default `True`\n- Methods for logging (`METHODS`), default `[\"get\",\"delete\",\"post\",\"put\",\"patch\",\"options\",\"head\"]`\n- Types of logging (`TYPES`), one of the `console`, `internal`, `syslog`, `file`, default `[\"console\"]`\n- Number of days to store the log entry (`TTL`), default `90`\n\nSyslog configuration parameters:\n\n- Syslog server address (`SYSLOG__HOST`), default `None`\n- Syslog server port (`SYSLOG__PORT`), default `6514`\n\nDatabase configuration parameters:\n\n- Use async mode (`DB__IS_ASYNC`), default `True`\n- Database connection string (`DB__URL`), default `None`\n- Database user (`DB__USER`), default `postgres`\n- Database password (`DB__PASSWORD`), default `None`\n- Database host (`DB__HOST`), default `localhost`\n- Database port (`DB__PORT`), default `5432`\n- Database name (`DB__NAME`), default `postgres`\n\nWhen using `fastapi_structlog.setup_logger`, the settings must be\npassed manually. An instance of the `LogSettings` class must be\npassed as an argument. You can import:\n\n```python\nfrom fastapi_structlog import LogSettings\n```\n\nThis may be convenient in case of expanding the settings.\n\nThe implementation of logging settings allows you to use it in\nexisting service settings in the form of `pydantic` models.\nJust add another field to your settings. You can use `BaseSettingsModel`\nas a base class for your settings. This class already includes the basic\nconfiguration, for example:\n\n- delimiter as `__`\n- ignoring environment variables with empty values\n\n```python\nfrom pathlib import Path\n\nimport structlog\nfrom pydantic_settings import SettingsConfigDict\n\nfrom fastapi_structlog import BaseSettingsModel, LogSettings, setup_logger\n\nlogger = structlog.get_logger()\n\nclass Settings(BaseSettingsModel):\n    log: LogSettings\n\n    model_config = SettingsConfigDict(\n        secrets_dir='/run/secrets' if Path('/run/secrets').exists() else None,\n    )\n\n\ndef main() -\u003e None:\n    settings = Settings()\n\n    setup_logger(settings.log)\n\n    logger.info('Start')\n\n\nif __name__ == '__main__':\n    main()\n\n```\n\nFor more information about the integration of logging\nsettings, see example №4 (`docs_src/example_4.py`).\n\n## Using logging in a FastAPI application\n\nThe use of the library in FasAPI application is for the most part\nsimilar to that described in the section\n[\"Logger configuration\"](#logger-configuration). To embed it in your\napplication, it is enough in the `main` function of the file `main.py` (or at\nany other entry point) before starting `uvicorn` (or another server) or\ndirectly in `lifespan`, use the registrar configuration functions. In all other\nplaces, it is enough to use `structlog.get_logger(log_name)` to get the logger.\nIt will be configured according to the settings specified when launching the\napplication.\n\nFor more information about integrating logging into a FasAPI\napplication, see example №2 (`docs_src/example_2.py`) or example №8\n(`docs_src/example_8.py`).\n\n## Using middleware in a FastAPI application\n\nThe library provides the following middleware:\n\n- `fastapi_structlog.middleware.CurrentScopeSetMiddleware` - Creating\nthe current context\n- `fastapi_structlog.middleware.StructlogMiddleware` - Adds a\npass-through request ID to the logs context. It should be used\ntogether with `asgi_correlation_id.middleware.CorrelationIdMiddleware`\n([github](https://github.com/snok/asgi-correlation-id)) or other\nmiddleware for generating end-to-end IDs.\n- `fastapi_structlog.middleware.AccessLogMiddleware` - Allows you\nto keep a log of access to the service.\n\nYou can add this middleware to a FasAPI application as follows:\n\n```python\napp = FastAPI(\n    title=\"Example API\",\n    version=\"1.0.0\",\n    middleware=[\n        Middleware(CurrentScopeSetMiddleware),\n        Middleware(CorrelationIdMiddleware),\n        Middleware(StructlogMiddleware),\n        Middleware(AccessLogMiddleware),\n    ],\n)\n```\n\nIt's worth noting that `CurrentScopeSetMiddleware` should come\nfirst, and `StructlogMiddleware` after `CorrelationIdMiddleware`!\n\nIn order for `AccessLogMiddleware` to use `structlog`, you need\nto initialize the logger before starting uvicorn (or another server).\nOtherwise, the standard logger will be used, which will be reported\nin the corresponding warning.\n\nFor more information about integrating logging into a FasAPI\napplication, see example №5 (`docs_src/example_5.py`).\n\n### Logging format\n\nThe `AccessLogMiddleware` middleware allows the use of the following parameters:\n\nName            | Alternative    | Description\n----------------|----------------|--------------------------------------\n`h`             | `client_addr`  | Client address (`IP:PORT`)\n`r`             |                | A query string indicating the type of request and the protocol version in the format `method path protocol`\n`R`             | `request_line` | Similar to the previous one, the format `method full_path protocol`, includes query parameters\n`t`             |                | Time\n`m`             |                | Method\n`U`             |                | URL\n`q`             |                | Query parameters\n`H`             |                | Protocol\n`s`             |                | Status\n`st`            |                | Name of the status\n`status`        |                | Status in the format `status name`\n`B`             | `b`            | [`Content-Length`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length)\n`f`             |                | [`Referer`](https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Referer)\n`a`             |                | [`User-Agent`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent)\n`T`             |                | Request time (integer number of seconds)\n`M`             |                | Request time (integer number of seconds * 1000)\n`D`             |                | Request time (integer number of seconds * 1_000_000)\n`L`             |                | Request time (seconds with 6 decimal places)\n`p`             |                | Process ID\n`l`             |                | -\n`u`             |                | -\n`session`       |                | User session data\n`full_path`     |                | URL with query parameters\n`r_summary`     |                | [`summary` field from APIRoute](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#summary-and-description)\n`r_description` |                | [`description` field from APIRoute](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#summary-and-description)\n\nUsing any parameter requires the inclusion of an expression\nin the format string `%(PARAM_NAME)s`.\n\nThe following format is used by default:\n\n```python\n%(client_addr)s - \"%(request_line)s\" %(status_code)s %(L)ss - \"%(a)s\"\n```\n\n## Using Sentry in a FastAPI application\n\nUsing Sentry is completely similar to using logging. You can use\n`fastapi_structlog.sentry.init_sentry` (with the `env_prefix` parameter)\nto configure Sentry using the built-in model\n(`fastapi_structlog.sentry.SentrySettings`) settings. In this case,\nthe parameters will be taken from the environment variables via\n`pydantic`. If necessary, you can specify `release`, `app_slug`\nand `version`. These parameters will be used when generating the\n`release` parameter for transmission to Sentry. The release is\nformed either from the explicitly passed `release` argument or\nin the `app_slug@version` format.\n\nAnother Sentry configuration option is to use\n`fastapi_structlog.sentry.setup_sentry`. However, in this case,\nyou must explicitly pass an instance of the settings\n`fastapi_structlog.sentry.SentrySettings` and the `release` parameter. In addition,\nyou can pass the `failed_request_status_codes` (status codes should be reported to Sentry)\nand `service_integration` (additional Sentry integrations) parameters.\n\nThe Sentry configuration parameters are as follows:\n\n- `dsn` - [Name of the data source](https://docs.sentry.io/product/sentry-basics/concepts/dsn-explainer/)\n- `env` - The name of the environment, see `fastapi_structlog.sentry.Environment`\n- `traces_sample_rate` - [Uniform sampling rate](https://docs.sentry.io/platforms/python/configuration/sampling/#configuring-the-transaction-sample-rate)\n- `log_integration` - Flag for using logging integration, by default `True`.\nFor more information, see [sentry docs](https://docs.sentry.io/platforms/python/integrations/logging/).\n- `log_integration_event_level` - Parameter `event_level` for `LoggingIntegration`, by default `None`.\n- `log_integration_level` -  - Parameter `level` for `LoggingIntegration`, by default `None`.\n- `sql_integration` - Flag for using\n[SQLAlchemy integration](https://docs.sentry.io/platforms/python/integrations/sqlalchemy/),\nby default `True`.\n\nBy inheriting from `fastapi_structlog.sentry.SentrySettings`, you can\nextend the Sentry configuration by adding the necessary\n[parameters](https://docs.sentry.io/platforms/python/configuration/options/)\n(see example №7 (`docs_src/example_7.py`).).\n\nAll parameters are optional! If there is no `dsn` Sentry will be ignored!\n\nThe implementation of Sentry settings in the settings of the general\nproject is similar to the one described in the section\n[\"Logger configuration\"](#logger-configuration).\n\nFor more information about integrating Sentry into the FasAPI\napplication, see example №3 (`docs_src/example_3.py`).\n\nTo use `sentry_sdk` with requests to other APIs, see example №6 (`docs_src/example_6.py`).\n\nIn addition, both functions accept the `service_integration` parameter.\nThis parameter is intended for inter-service interaction and can be\nuseful for repeated requests (for example, to track the delay before\na repeat request, to track subqueries to other services, to monitor\nthe time for data serialization, and more).\n\n## Logging into the database\n\nIf you want to save logs to a database, then you need to declare a table\nmodel. The library provides a basic `LogModel` model that you can import as:\n\n```python\nfrom fastapi_structlog.db_handler import LogModel\n```\n\nThis model inherits SQLModel and is a **data model**, that is, it does\nnot have the `table=True` parameter. Therefore, you need to make a class\nthat will inherit this model and add `table=True`. You can also add new\nfields or write your own model altogether. However, the `fastapi_structlog`\nrelies on it to be the Inheritor of the `SQLModel`:\n\n```python\nclass Log(LogModel, table=True):\n    \"\"\"Log table.\"\"\"\n```\n\nYou should use one of the logger initialization functions and pass\nyour model there, as well as the database connection string. This may be\na different database from your main one.\n\n```python\nengine = create_async_engine(DB_URL)\n\nqueue_listener = setup_logger(\n    settings.log,\n    model=Log,\n    db_url=settings.log.db.make_url(),\n)\n\nlogger = structlog.get_logger()\n```\n\nUse `lifespan` to start and stop `queue_listener`, for example:\n\n```python\n@asynccontextmanager\nasync def lifespan(_: FastAPI) -\u003e AsyncGenerator[None, None]:\n    async with engine.begin() as conn:\n        await conn.run_sync(Log.metadata.create_all)\n\n    if queue_listener:\n        queue_listener.start()\n\n    yield\n\n    if queue_listener:\n        queue_listener.stop()\n```\n\nYou must pass `lifespan` as a parameter to the `FastAPI` class. This is the\nend of logging into the database.\n\nYou can read the sample code in `docs_src/example_8.py`\n\n## Examples\n\nFor other usage docs_src, see `docs_src`:\n\n- `example_1` - simple example\n- `example_2` - example using `fastapi` and `uvicorn`\n- `example_3` - example using `fastapi`, `uvicorn` and `sentry`\n- `example_4` - example with the integration of logging settings into the application settings\n- `example_5` - example using middleware\n- `example_6` - example using Sentry and nested calls to other APIs\n- `example_7` - expanding settings\n- `example_8` - logging logs to the database with redefinition of some fields\n\n## Dependencies\n\nThe following dependencies are used here:\n\n- Python 3.9\n- pydantic (for validate the settings)\n- structlog (for set up the logger)\n- sentry_sdk\n- SQLModel (for database integration)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredb0%2Ffastapi-logger","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fredb0%2Ffastapi-logger","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredb0%2Ffastapi-logger/lists"}