Skip to content

feat: add structured logs to application output

Stan Hu requested to merge sh-add-structlog into main

This commit removes the default Uvicorn loggers in favor of a structured, JSON log formatter that includes a correlation ID and duration_s field. This log could be ingested to Elasticsearch for analysis and searching.

Relates to #25 (closed)

Example logs:

Before

INFO:     Started server process [27698]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:9999 (Press CTRL+C to quit)
ERROR:    2023-04-18 14:47:46,885 - "No authorization header presented"
INFO:     127.0.0.1:58067 - "GET / HTTP/1.1" 401 Unauthorized

After

{"logger": "uvicorn.error", "level": "info", "timestamp": "2023-04-18T21:45:50.223635Z", "message": "Started server process [27260]"}
{"logger": "uvicorn.error", "level": "info", "timestamp": "2023-04-18T21:45:50.223719Z", "message": "Waiting for application startup."}
{"logger": "uvicorn.error", "level": "info", "timestamp": "2023-04-18T21:45:50.228986Z", "message": "Application startup complete."}
{"logger": "uvicorn.error", "level": "info", "timestamp": "2023-04-18T21:45:50.230332Z", "message": "Uvicorn running on http://0.0.0.0:9999 (Press CTRL+C to quit)"}
{"correlation_id": "b4f49867b1b74d40ae7e5fe6cf298117", "logger": "codesuggestions", "level": "error", "timestamp": "2023-04-18T21:45:51.573096Z", "message": "No authorization header presented"}
{"url": "http://localhost:9999/", "path": "/", "status_code": 401, "method": "GET", "correlation_id": "b4f49867b1b74d40ae7e5fe6cf298117", "http_version": "1.1", "client_ip": "127.0.0.1", "client_port": 58025, "duration_s": 0.000543375, "logger": "api.access", "level": "info", "timestamp": "2023-04-18T21:45:51.573458Z", "message": "127.0.0.1:58025 - \"GET / HTTP/1.1\" 401"}
Edited by Mon Ray

Merge request reports