-
Notifications
You must be signed in to change notification settings - Fork 5.3k
[WEB-5575]feat: enhance APITokenLogMiddleware to support logging to MongoDB #8241
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 all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
889da74
feat: enhance APITokenLogMiddleware to support logging to MongoDB
pablohashescobar 415f6e3
fix: improve MongoDB availability checks in APITokenLogMiddleware
pablohashescobar 6a95341
feat: implement logging functionality in logger_task for API activity
pablohashescobar acc3970
refactor: simplify MongoDB logging in logger_task and middleware
pablohashescobar e83ddd2
feat: add Celery task decorator to process_logs function in logger_task
pablohashescobar 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
Some comments aren't visible on the classic Files Changed page.
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 |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| # Python imports | ||
| import logging | ||
| from typing import Optional, Dict, Any | ||
|
|
||
| # Third party imports | ||
| from pymongo.collection import Collection | ||
| from celery import shared_task | ||
|
|
||
| # Django imports | ||
| from plane.settings.mongo import MongoConnection | ||
| from plane.utils.exception_logger import log_exception | ||
| from plane.db.models import APIActivityLog | ||
|
|
||
|
|
||
| logger = logging.getLogger("plane.worker") | ||
|
|
||
|
|
||
| def get_mongo_collection() -> Optional[Collection]: | ||
| """ | ||
| Returns the MongoDB collection for external API activity logs. | ||
| """ | ||
| if not MongoConnection.is_configured(): | ||
| logger.info("MongoDB not configured") | ||
| return None | ||
|
|
||
| try: | ||
| return MongoConnection.get_collection("api_activity_logs") | ||
| except Exception as e: | ||
| logger.error(f"Error getting MongoDB collection: {str(e)}") | ||
| log_exception(e) | ||
| return None | ||
|
|
||
|
|
||
| def safe_decode_body(content: bytes) -> Optional[str]: | ||
| """ | ||
| Safely decodes request/response body content, handling binary data. | ||
| Returns "[Binary Content]" if the content is binary, or a string representation of the content. | ||
| Returns None if the content is None or empty. | ||
| """ | ||
| # If the content is None, return None | ||
| if content is None: | ||
| return None | ||
|
|
||
| # If the content is an empty bytes object, return None | ||
| if content == b"": | ||
| return None | ||
|
|
||
| # Check if content is binary by looking for common binary file signatures | ||
| if content.startswith(b"\x89PNG") or content.startswith(b"\xff\xd8\xff") or content.startswith(b"%PDF"): | ||
| return "[Binary Content]" | ||
|
|
||
| try: | ||
| return content.decode("utf-8") | ||
| except UnicodeDecodeError: | ||
| return "[Could not decode content]" | ||
|
|
||
|
|
||
| def log_to_mongo(log_document: Dict[str, Any]) -> bool: | ||
| """ | ||
| Logs the request to MongoDB if available. | ||
| """ | ||
| mongo_collection = get_mongo_collection() | ||
| if mongo_collection is None: | ||
| logger.error("MongoDB not configured") | ||
| return False | ||
|
|
||
| try: | ||
| mongo_collection.insert_one(log_document) | ||
| return True | ||
| except Exception as e: | ||
| log_exception(e) | ||
| return False | ||
|
|
||
|
|
||
| def log_to_postgres(log_data: Dict[str, Any]) -> bool: | ||
| """ | ||
| Fallback to logging to PostgreSQL if MongoDB is unavailable. | ||
| """ | ||
| try: | ||
| APIActivityLog.objects.create(**log_data) | ||
| return True | ||
| except Exception as e: | ||
| log_exception(e) | ||
| return False | ||
|
|
||
|
|
||
| @shared_task | ||
| def process_logs(log_data: Dict[str, Any], mongo_log: Dict[str, Any]) -> None: | ||
| """ | ||
| Process logs to save to MongoDB or Postgres based on the configuration | ||
| """ | ||
|
|
||
| if MongoConnection.is_configured(): | ||
| log_to_mongo(mongo_log) | ||
| else: | ||
| log_to_postgres(log_data) |
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.