question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to log operation id and status for each route?

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

@app.middleware("http")
async def log(request, call_next):
    response = call_next(request)
    if response.status_code >= 300:
        return response
    operation_id = get_operation_id_somehow() # is this possible?
    print("LOG", operation_id, get_access_token(request))
    return response

Description

I want to log the Operation ID, as well as the access token (from the request) for all requests that did not error, is this at all possible right now?

Given that I want to do this for all endpoints, using a middleware seems reasonable, but they have no way of accessing the route information (including the operation id). I can get the other bits of information from the requests/response no problem.

I also considered using a dependency, but even dependencies seem unable to have access to the operation id.

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.65.2

Python Version

Python 3.9.1

Additional Context

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
ifigueroapcommented, Sep 10, 2021

I’m currently working on the same situation… this seems to work so far:

"""Instrumentation for registering requests and responses."""

import logging
from typing import Callable

from fastapi import Request, Response
from fastapi.routing import APIRoute

logger = logging.getLogger(__name__)


class LoggingRoute(APIRoute):  # noqa
    def get_route_handler(self) -> Callable:  # noqa
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:  # noqa
            logger.warning("====REQUEST SCOPE====")
            logger.warning(request.scope)
            logger.warning("=====================")

            logger.warning("====REQUEST BODY JSON====")
            body_json = await request.json()
            logger.warning(body_json)
            logger.warning("=====================")

            response = await original_route_handler(request)

            logger.warning("====RESPONSE JSON====")
            logger.warning(response.body)
            logger.warning("=====================")
            return response

        return custom_route_handler

However, you need to inject this class into the router before adding routes to it because the (internal?) add_route method uses the route_class constructor to create the routes, hence it cannot be overriden afterwards…

An example on how to do this:

router = APIRouter(prefix="/foo", route_class=LoggingRoute)

@router.post(...)
def post_method(...)
    # etc


0reactions
ojiicommented, Nov 17, 2021

I’ve ended up using the solution suggested in https://github.com/tiangolo/fastapi/issues/3877#issuecomment-916162837

Read more comments on GitHub >

github_iconTop Results From Across the Web

Operations management - Azure Data Explorer | Microsoft Learn
Up to one record indicates the terminal state of Completed or Failed . This mode is used when the command doesn't indicate the...
Read more >
How to get the Operation ID in a HTTPTrigger Azure Function ...
You can use Activity.Current.RootId to get Operation Id inside a HTTP Trigger in portal. Code: #r "Newtonsoft.Json" using System.
Read more >
Path Operation Advanced Configuration - FastAPI
You can set the OpenAPI operationId to be used in your path operation with the parameter operation_id . You would have to make...
Read more >
Paths and Operations - Swagger
All paths are relative to the API server URL. The full request URL is constructed as <server-url>/path . Global servers can also be...
Read more >
Command Line Interface — Schemathesis 3.17.5 documentation
By default, Schemathesis runs tests for all operations, ... --endpoint / -E . Operation path; ... The response status is not defined in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found