Files
Fringg 1f0fef114b refactor: complete structlog migration with contextvars, kwargs, and logging hardening
- Add ContextVarsMiddleware for automatic user_id/chat_id/username binding
  via structlog contextvars (aiogram) and http_method/http_path (FastAPI)
- Use bound_contextvars() context manager instead of clear_contextvars()
  to safely restore previous state instead of wiping all context
- Register ContextVarsMiddleware as outermost middleware (before GlobalError)
  so all error logs include user context
- Replace structlog.get_logger() with structlog.get_logger(__name__) across
  270 calls in 265 files for meaningful logger names
- Switch wrapper_class from BoundLogger to make_filtering_bound_logger()
  for pre-processor level filtering (performance optimization)
- Migrate 1411 %-style positional arg logger calls to structlog kwargs
  style across 161 files via AST script
- Migrate log_rotation_service.py from stdlib logging to structlog
- Add payment module prefixes to TelegramNotifierProcessor.IGNORED_LOGGER_PREFIXES
  and ExcludePaymentFilter.PAYMENT_MODULES to prevent payment data leaking
  to Telegram notifications and general log files
- Fix LoggingMiddleware: add from_user null-safety for channel posts,
  switch time.time() to time.monotonic() for duration measurement
- Remove duplicate logger assignments in purchase.py, config.py,
  inline.py, and admin/payments.py
2026-02-16 09:18:12 +03:00

116 lines
3.6 KiB
Python

import structlog
from aiogram import Dispatcher, F, types
from aiogram.exceptions import TelegramBadRequest, TelegramForbiddenError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from app.keyboards.admin import (
get_admin_report_result_keyboard,
get_admin_reports_keyboard,
)
from app.localization.texts import get_texts
from app.services.reporting_service import (
ReportingServiceError,
ReportPeriod,
reporting_service,
)
from app.utils.decorators import admin_required, error_handler
logger = structlog.get_logger(__name__)
@admin_required
@error_handler
async def show_reports_menu(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
) -> None:
await callback.message.edit_text(
'📊 <b>Отчеты</b>\n\nВыберите период, чтобы отправить отчет в админский топик.',
reply_markup=get_admin_reports_keyboard(db_user.language),
parse_mode='HTML',
)
await callback.answer()
@admin_required
@error_handler
async def send_daily_report(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
) -> None:
await _send_report(callback, ReportPeriod.DAILY, db_user.language)
@admin_required
@error_handler
async def send_weekly_report(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
) -> None:
await _send_report(callback, ReportPeriod.WEEKLY, db_user.language)
@admin_required
@error_handler
async def send_monthly_report(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
) -> None:
await _send_report(callback, ReportPeriod.MONTHLY, db_user.language)
async def _send_report(
callback: types.CallbackQuery,
period: ReportPeriod,
language: str,
) -> None:
try:
report_text = await reporting_service.send_report(period, send_to_topic=True)
except ReportingServiceError as exc:
logger.warning('Не удалось отправить отчет', exc=exc)
await callback.answer(str(exc), show_alert=True)
return
except Exception as exc:
logger.error('Непредвиденная ошибка при отправке отчета', exc=exc)
await callback.answer('Не удалось отправить отчет. Попробуйте позже.', show_alert=True)
return
await callback.message.answer(
report_text,
reply_markup=get_admin_report_result_keyboard(language),
)
await callback.answer('Отчет отправлен в топик')
@admin_required
@error_handler
async def close_report_message(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
) -> None:
texts = get_texts(db_user.language)
try:
await callback.message.delete()
except (TelegramBadRequest, TelegramForbiddenError) as exc:
logger.warning('Не удалось закрыть сообщение отчета', exc=exc)
await callback.answer(texts.t('REPORT_CLOSE_ERROR', 'Не удалось закрыть отчет.'), show_alert=True)
return
await callback.answer(texts.t('REPORT_CLOSED', 'Отчет закрыт.'))
def register_handlers(dp: Dispatcher) -> None:
dp.callback_query.register(show_reports_menu, F.data == 'admin_reports')
dp.callback_query.register(send_daily_report, F.data == 'admin_reports_daily')
dp.callback_query.register(send_weekly_report, F.data == 'admin_reports_weekly')
dp.callback_query.register(send_monthly_report, F.data == 'admin_reports_monthly')
dp.callback_query.register(close_report_message, F.data == 'admin_close_report')