Create api_logger.py
Browse files- app/services/api_logger.py +50 -0
app/services/api_logger.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import Callable, Optional
|
| 6 |
+
from zoneinfo import ZoneInfo
|
| 7 |
+
|
| 8 |
+
from motor.motor_asyncio import AsyncIOMotorCollection
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ApiLogger:
|
| 14 |
+
"""Persists API invocation metadata for observability/auditing."""
|
| 15 |
+
|
| 16 |
+
def __init__(self, collection_getter: Callable[[], AsyncIOMotorCollection]) -> None:
|
| 17 |
+
self._collection_getter = collection_getter
|
| 18 |
+
|
| 19 |
+
def _collection(self) -> AsyncIOMotorCollection:
|
| 20 |
+
return self._collection_getter()
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def _current_ist_timestamp() -> str:
|
| 24 |
+
now = datetime.now(ZoneInfo("Asia/Kolkata"))
|
| 25 |
+
return now.strftime("%d-%m-%Y %H:%M:%S:%Z")
|
| 26 |
+
|
| 27 |
+
async def log_categorization(
|
| 28 |
+
self,
|
| 29 |
+
*,
|
| 30 |
+
name: str,
|
| 31 |
+
status: str,
|
| 32 |
+
response_time: float,
|
| 33 |
+
user_id: Optional[str],
|
| 34 |
+
error_message: Optional[str] = None,
|
| 35 |
+
) -> None:
|
| 36 |
+
doc = {
|
| 37 |
+
"name": name,
|
| 38 |
+
"status": status,
|
| 39 |
+
"date": self._current_ist_timestamp(),
|
| 40 |
+
"response_time": round(response_time, 3),
|
| 41 |
+
}
|
| 42 |
+
if user_id:
|
| 43 |
+
doc["user_id"] = user_id
|
| 44 |
+
if error_message:
|
| 45 |
+
doc["error_message"] = error_message
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
await self._collection().insert_one(doc)
|
| 49 |
+
except Exception:
|
| 50 |
+
logger.exception("Failed to write categorize API log")
|