[Python] How do I get my FastAPI application's console log in JSON format with a different...

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI application where I would like to get the default logs written to STDOUT with the following data in JSON format:

    App logs should look like this:

    {
    "XYZ": {
    "log": {
    "level": "info",
    "type": "app",
    "timestamp": "2022-01-16T08:30:08.181Z",
    "file": "api/predictor/predict.py",
    "line": 34,
    "threadId": 435454,
    "message": "API Server started on port 8080 (development)"
    }
    }
    }


    Access logs should look like this:

    {
    "XYZ": {
    "log": {
    "level": "info",
    "type": "access",
    "timestamp": "2022-01-16T08:30:08.181Z",
    "message": "GET /app/health 200 6ms"
    },
    "req": {
    "url": "/app/health",
    "headers": {
    "host": "localhost:8080",
    "user-agent": "curl/7.68.0",
    "accept": "*/*"
    },
    "method": "GET",
    "httpVersion": "1.1",
    "originalUrl": "/app/health",
    "query": {}
    },
    "res": {
    "statusCode": 200,
    "body": {
    "statusCode": 200,
    "status": "OK"
    }
    }
    }
    }


    What I've tried:

    I tried using the json-logging package for this. Using this example, I'm able to access the request logs in JSON and change the structure. But, I'm unable to find how to access and change the app logs.

    Current output logs structure:

    {"written_at": "2022-01-28T09:31:38.686Z", "written_ts": 1643362298686910000, "msg":
    "Started server process [12919]", "type": "log", "logger": "uvicorn.error", "thread":
    "MainThread", "level": "INFO", "module": "server", "line_no": 82, "correlation_id":
    "-"}

    {"written_at": "2022-01-28T09:31:38.739Z", "written_ts": 1643362298739838000, "msg":
    "Started server process [12919]", "type": "log", "logger": "uvicorn.error", "thread":
    "MainThread", "level": "INFO", "module": "server", "line_no": 82, "correlation_id":
    "-"}

    {"written_at": "2022-01-28T09:31:38.739Z", "written_ts": 1643362298739951000, "msg":
    "Waiting for application startup.", "type": "log", "logger": "uvicorn.error",
    "thread": "MainThread", "level": "INFO", "module": "on", "line_no": 45,
    "correlation_id": "-"}

    Continue reading...

Compartilhe esta Página