Files
AnonBot/services/infrastructure/db_metrics_decorator.py

70 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Декоратор для автоматического сбора метрик базы данных
"""
import time
import functools
from typing import Callable, Any
from .metrics import get_metrics_service
from .logger import get_logger
def track_db_operation(operation: str, table: str):
"""
Декоратор для отслеживания операций с базой данных
Args:
operation: Тип операции (SELECT, INSERT, UPDATE, DELETE)
table: Название таблицы
"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
async def wrapper(*args, **kwargs) -> Any:
metrics_service = get_metrics_service()
logger = get_logger(__name__)
start_time = time.time()
try:
result = await func(*args, **kwargs)
duration = time.time() - start_time
# Записываем успешную операцию
metrics_service.record_db_query(operation, table, "success", duration)
return result
except Exception as e:
duration = time.time() - start_time
# Записываем неудачную операцию
metrics_service.record_db_query(operation, table, "error", duration)
metrics_service.increment_errors(type(e).__name__, "database_operation")
logger.error(f"Database operation failed: {operation} on {table}: {e}")
raise
return wrapper
return decorator
def track_db_connection(func: Callable) -> Callable:
"""
Декоратор для отслеживания соединений с базой данных
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs) -> Any:
metrics_service = get_metrics_service()
logger = get_logger(__name__)
try:
result = await func(*args, **kwargs)
return result
except Exception as e:
# Записываем только ошибки, не соединения
metrics_service.increment_errors(type(e).__name__, "database_connection")
logger.error(f"Database connection failed: {e}")
raise
return wrapper