-
Notifications
You must be signed in to change notification settings - Fork 31
Add logger middleware #327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
f8bf866
add logger middleware
suhasunni 38be68c
fix apostrophe
suhasunni 223e4eb
update body_iterator
suhasunni f0c242f
fix body_iterator
suhasunni e469f6d
add loguru to requirements.txt
suhasunni 87ab0da
add logger middleware
suhasunni 31a67b6
change user_id name
suhasunni 425f533
fix pr changes except call_next type
suhasunni e46c96c
fix body_iterator attribute issue
suhasunni bcd72d5
fix add_excluded_endpoints bug
suhasunni 890d367
change log message based on response type
suhasunni 66479c8
revert to old changes
suhasunni e1d5709
change call_next type hint
suhasunni 7a26e9c
add type: ignore
suhasunni 843befa
move comment
suhasunni dec73d1
add request_body_bytes
suhasunni 5f0cf50
cast response_size to str
suhasunni 93a91e7
use pref_counter() and add uuid
suhasunni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,47 @@ | ||
| from fastapi import Request, Response | ||
| from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint | ||
| from loguru import logger | ||
| from time import time | ||
| from sys import getsizeof | ||
| from typing import List | ||
|
|
||
|
|
||
| #add any endpoints we don't want logged here, e.g "/example/endpoint" | ||
| excluded_endpoints: List[str] = [] | ||
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| class LoggerMiddleware(BaseHTTPMiddleware): | ||
| """Middleware that logs the request and response""" | ||
|
|
||
| async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response: | ||
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Logs the request and response""" | ||
| # TODO: Add logging here | ||
| start_time = time() | ||
| response = await call_next(request) | ||
| return response | ||
| process_time = time() - start_time | ||
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if request.url.path in excluded_endpoints: | ||
| return response | ||
|
|
||
| request_body = await request.body() | ||
| request_size = getsizeof(request_body) | ||
| # TODO: update this based on userID header name | ||
| request_user_id = request.headers.get("user_id", "Anonymous") | ||
| request_params = dict(request.query_params) | ||
|
|
||
| logger.info(f"REQUEST | Method: {request.method} | URL: {request.url.path} | User id: {request_user_id} | Params: {request_params} | Size: {request_size} bytes.") | ||
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if response.status_code >= 500: | ||
| logger_severity = logger.critical | ||
| elif response.status_code >= 400: | ||
Yarik-Popov marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| logger_severity = logger.error | ||
| else: | ||
| logger_severity = logger.info | ||
|
|
||
| response_body = b''.join([chunk async for chunk in response.body_iterator]) | ||
| response_size = getsizeof(response_body) | ||
|
|
||
| logger_severity(f"RESPONSE | Status: {response.status_code} | Response: {response_body.decode(errors='ignore')} | Size: {response_size} bytes | Time Elasped: {process_time:.3f}.") | ||
|
|
||
| return Response( | ||
| content=response_body, | ||
| status_code=response.status_code, | ||
| headers=dict(response.headers), | ||
| media_type=response.media_type, | ||
| ) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.