notifications.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import hashlib
  2. import os
  3. import subprocess
  4. import threading
  5. from contextlib import contextmanager
  6. from datetime import datetime, timedelta
  7. from typing import Any
  8. from loguru import logger
  9. from sqlalchemy import and_, desc, func
  10. from sqlalchemy.orm import Session
  11. from database.database import Notification, get_session
  12. # Import Telegram integration (optional - fails gracefully if not configured)
  13. try:
  14. from services.notifications.telegram_integration import send_telegram_notification
  15. TELEGRAM_AVAILABLE = True
  16. except Exception as e:
  17. logger.debug(f"Telegram integration not available: {e}")
  18. TELEGRAM_AVAILABLE = False
  19. send_telegram_notification = None
  20. # Configuration constants
  21. CLEANUP_KEEP_COUNT = 100
  22. DEFAULT_DEDUPLICATE_HOURS = 1
  23. # Notification thresholds
  24. FAILED_AUTH_THRESHOLD = 15
  25. DENIED_REQUESTS_THRESHOLD = 20
  26. SUSPICIOUS_IP_THRESHOLD = 6000
  27. CRITICAL_IP_THRESHOLD = 20000
  28. MAX_IPS_TO_REPORT = 5
  29. # User activity thresholds
  30. HIGH_ACTIVITY_THRESHOLD = 100
  31. HIGH_USAGE_GB_THRESHOLD = 20.0
  32. MAX_USERS_TO_REPORT = 3
  33. # System health thresholds
  34. SQUID_LOG_SIZE_WARNING_MB = 500
  35. SQUID_LOG_STALE_HOURS = 24
  36. DISK_CRITICAL_GB = 1
  37. DISK_WARNING_GB = 5
  38. # Monitor intervals (in minutes)
  39. CHECK_COMMITS_INTERVAL = 30
  40. CHECK_SYSTEM_INTERVAL = 5
  41. CHECK_SQUID_LOG_INTERVAL = 10
  42. CHECK_SECURITY_INTERVAL = 3
  43. CHECK_USER_ACTIVITY_INTERVAL = 15
  44. # Global variable for Socket.IO
  45. socketio = None
  46. # Global stop event for notification monitor
  47. _monitor_stop_event = None
  48. _monitor_thread = None
  49. def set_socketio_instance(sio):
  50. global socketio
  51. socketio = sio
  52. @contextmanager
  53. def get_db_session():
  54. """Context manager for database sessions"""
  55. db = get_session()
  56. try:
  57. yield db
  58. db.commit()
  59. except Exception:
  60. db.rollback()
  61. raise
  62. finally:
  63. db.close()
  64. def stop_notification_monitor():
  65. """Stop the notification monitor thread"""
  66. global _monitor_stop_event, _monitor_thread
  67. if _monitor_stop_event:
  68. _monitor_stop_event.set()
  69. if _monitor_thread and _monitor_thread.is_alive():
  70. _monitor_thread.join(timeout=5)
  71. logger.info("Notification monitor stopped")
  72. def _generate_message_hash(message: str, source: str, notification_type: str) -> str:
  73. """Generate SHA256 hash for deduplication"""
  74. content = f"{source}:{notification_type}:{message}"
  75. return hashlib.sha256(content.encode()).hexdigest()
  76. def _check_duplicate_notification(
  77. db: Session, message_hash: str, hours: int = 24
  78. ) -> Notification | None:
  79. """Check if a similar notification exists in the last N hours"""
  80. time_threshold = datetime.now() - timedelta(hours=hours)
  81. return (
  82. db.query(Notification)
  83. .filter(
  84. and_(
  85. Notification.message_hash == message_hash,
  86. Notification.created_at >= time_threshold,
  87. )
  88. )
  89. .first()
  90. )
  91. def set_commit_notifications(has_updates, messages):
  92. """Keep for compatibility"""
  93. # Convert commits to system notifications
  94. if has_updates and messages:
  95. for msg in messages:
  96. add_notification("info", f"Commit: {msg}", "fa-code-branch", "git")
  97. def get_commit_notifications() -> dict[str, Any]:
  98. """Keep for compatibility with existing code"""
  99. with get_db_session() as db:
  100. git_notifications = (
  101. db.query(Notification).filter(Notification.source == "git").all()
  102. )
  103. return {
  104. "has_updates": len(git_notifications) > 0,
  105. "commits": [n.message.replace("Commit: ", "") for n in git_notifications],
  106. }
  107. def add_notification(
  108. notification_type: str,
  109. message: str,
  110. icon: str | None = None,
  111. source: str = "system",
  112. deduplicate_hours: int = DEFAULT_DEDUPLICATE_HOURS,
  113. send_telegram: bool = True,
  114. ) -> dict[str, Any] | None:
  115. """Adds a notification to the database and emits via Socket.IO if configured
  116. Args:
  117. notification_type: Type of notification ('info', 'warning', 'error', 'success')
  118. message: Notification message
  119. icon: FontAwesome icon class (optional)
  120. source: Source of the notification ('squid', 'system', 'security', 'users', 'git')
  121. deduplicate_hours: Hours to check for duplicate notifications
  122. send_telegram: Send notification to Telegram (default: True)
  123. Returns:
  124. Dictionary with notification data or None if it was a duplicate
  125. """
  126. with get_db_session() as db:
  127. message_hash = _generate_message_hash(message, source, notification_type)
  128. # Check for duplicates
  129. existing = _check_duplicate_notification(
  130. db, message_hash, hours=deduplicate_hours
  131. )
  132. if existing:
  133. # Update existing notification count and timestamp
  134. existing.count += 1
  135. existing.updated_at = datetime.now()
  136. existing.read = 0 # Mark as unread again
  137. # Create dict before closing session
  138. notification_dict = _notification_to_dict(existing)
  139. # Emit update via Socket.IO
  140. if socketio:
  141. unread_count = _get_unread_count(db)
  142. socketio.emit(
  143. "notification_updated",
  144. {
  145. "notification": notification_dict,
  146. "unread_count": unread_count,
  147. },
  148. )
  149. return notification_dict
  150. # Create new notification
  151. notification = Notification(
  152. type=notification_type,
  153. message=message,
  154. message_hash=message_hash,
  155. icon=icon or get_default_icon(notification_type),
  156. source=source,
  157. read=0,
  158. count=1,
  159. created_at=datetime.now(),
  160. )
  161. db.add(notification)
  162. db.flush() # Flush to get ID without committing
  163. db.refresh(notification)
  164. # Create dict before cleanup
  165. notification_dict = _notification_to_dict(notification)
  166. # Clean old notifications (keep last N)
  167. _cleanup_old_notifications(db, keep_count=CLEANUP_KEEP_COUNT)
  168. # Emit via Socket.IO if configured
  169. if socketio:
  170. unread_count = _get_unread_count(db)
  171. socketio.emit(
  172. "new_notification",
  173. {
  174. "notification": notification_dict,
  175. "unread_count": unread_count,
  176. },
  177. )
  178. # Send to Telegram if enabled and requested
  179. if send_telegram and TELEGRAM_AVAILABLE and send_telegram_notification:
  180. try:
  181. send_telegram_notification(
  182. notification_type=notification_type, message=message, source=source
  183. )
  184. except Exception as e:
  185. logger.error(f"Failed to send Telegram notification: {e}")
  186. return notification_dict
  187. def _notification_to_dict(notification: Notification) -> dict:
  188. """Convert Notification object to dictionary"""
  189. return {
  190. "id": notification.id,
  191. "type": notification.type,
  192. "message": notification.message,
  193. "icon": notification.icon,
  194. "timestamp": notification.created_at.isoformat(),
  195. "time": _format_time_ago(notification.created_at),
  196. "read": bool(notification.read),
  197. "source": notification.source,
  198. "count": notification.count,
  199. }
  200. def _format_time_ago(timestamp: datetime) -> str:
  201. """Format timestamp as 'hace X tiempo'"""
  202. now = datetime.now()
  203. diff = now - timestamp
  204. minutes = int(diff.total_seconds() / 60)
  205. hours = int(diff.total_seconds() / 3600)
  206. days = int(diff.total_seconds() / 86400)
  207. if minutes < 1:
  208. return "Hace unos momentos"
  209. elif minutes < 60:
  210. return f"Hace {minutes} minuto{'s' if minutes > 1 else ''}"
  211. elif hours < 24:
  212. return f"Hace {hours} hora{'s' if hours > 1 else ''}"
  213. else:
  214. return f"Hace {days} día{'s' if days > 1 else ''}"
  215. def _get_unread_count(db: Session) -> int:
  216. """Get count of unread notifications"""
  217. return db.query(func.count(Notification.id)).filter(Notification.read == 0).scalar()
  218. def _cleanup_old_notifications(db: Session, keep_count: int = CLEANUP_KEEP_COUNT):
  219. """Remove old notifications, keeping only the most recent ones"""
  220. total_count = db.query(func.count(Notification.id)).scalar()
  221. if total_count > keep_count:
  222. # Get IDs of notifications to keep
  223. keep_ids_query = (
  224. db.query(Notification.id)
  225. .order_by(desc(Notification.created_at))
  226. .limit(keep_count)
  227. .subquery()
  228. )
  229. # Delete old notifications in one query
  230. deleted = (
  231. db.query(Notification)
  232. .filter(Notification.id.notin_(keep_ids_query))
  233. .delete(synchronize_session=False)
  234. )
  235. if deleted > 0:
  236. logger.info(f"Cleaned up {deleted} old notifications")
  237. def get_default_icon(notification_type):
  238. icons = {
  239. "info": "fa-info-circle",
  240. "warning": "fa-exclamation-triangle",
  241. "error": "fa-times-circle",
  242. "success": "fa-check-circle",
  243. }
  244. return icons.get(notification_type, "fa-bell")
  245. def get_all_notifications(
  246. limit: int = 10, page: int = 1, per_page: int = 20
  247. ) -> dict[str, Any]:
  248. """Gets all system notifications with pagination support from database"""
  249. with get_db_session() as db:
  250. # Get total count
  251. total_notifications = db.query(func.count(Notification.id)).scalar() or 0
  252. # Get unread count
  253. unread_count = (
  254. db.query(func.count(Notification.id))
  255. .filter(Notification.read == 0)
  256. .scalar()
  257. or 0
  258. )
  259. # Calculate pagination
  260. start_index = (page - 1) * per_page
  261. # Get paginated notifications
  262. notifications = (
  263. db.query(Notification)
  264. .order_by(desc(Notification.created_at))
  265. .offset(start_index)
  266. .limit(per_page)
  267. .all()
  268. )
  269. # Convert to dict
  270. notifications_list = [_notification_to_dict(n) for n in notifications]
  271. # Calculate pagination metadata
  272. total_pages = (
  273. (total_notifications + per_page - 1) // per_page
  274. if total_notifications > 0
  275. else 1
  276. )
  277. return {
  278. "unread_count": int(unread_count),
  279. "notifications": notifications_list,
  280. "pagination": {
  281. "current_page": page,
  282. "per_page": per_page,
  283. "total_pages": total_pages,
  284. "total_notifications": int(total_notifications),
  285. "has_prev": page > 1,
  286. "has_next": page < total_pages,
  287. },
  288. }
  289. def mark_notifications_read(notification_ids: list[int]) -> int:
  290. with get_db_session() as db:
  291. updated = (
  292. db.query(Notification)
  293. .filter(Notification.id.in_(notification_ids))
  294. .update(
  295. {"read": 1, "updated_at": datetime.now()}, synchronize_session=False
  296. )
  297. )
  298. logger.info(f"Marked {updated} notifications as read")
  299. return updated
  300. def delete_notification(notification_id: int) -> bool:
  301. with get_db_session() as db:
  302. deleted = (
  303. db.query(Notification)
  304. .filter(Notification.id == notification_id)
  305. .delete(synchronize_session=False)
  306. )
  307. if deleted:
  308. logger.info(f"Deleted notification {notification_id}")
  309. return deleted > 0
  310. def delete_all_notifications() -> int:
  311. with get_db_session() as db:
  312. deleted = db.query(Notification).delete(synchronize_session=False)
  313. logger.info(f"Deleted all {deleted} notifications")
  314. return deleted
  315. def check_squid_log_health():
  316. """Checks Squid logs health"""
  317. try:
  318. log_file = os.getenv("SQUID_LOG", "/var/log/squid/access.log")
  319. if not os.path.exists(log_file):
  320. add_notification(
  321. "error",
  322. f"Archivo de log de Squid no encontrado: {log_file}",
  323. "fa-file-exclamation",
  324. "squid",
  325. )
  326. return
  327. stat_info = os.stat(log_file)
  328. file_size_mb = stat_info.st_size / (1024 * 1024)
  329. # Check file size
  330. if file_size_mb > SQUID_LOG_SIZE_WARNING_MB:
  331. add_notification(
  332. "warning",
  333. f"Log de Squid muy grande: {file_size_mb:.1f}MB",
  334. "fa-file-alt",
  335. "squid",
  336. )
  337. # Check last modification
  338. last_modified = datetime.fromtimestamp(stat_info.st_mtime)
  339. hours_since_update = (datetime.now() - last_modified).total_seconds() / 3600
  340. if hours_since_update > SQUID_LOG_STALE_HOURS:
  341. add_notification(
  342. "warning",
  343. f"Log de Squid no actualizado por más de {int(hours_since_update)}h",
  344. "fa-clock",
  345. "squid",
  346. )
  347. except OSError as e:
  348. logger.error(f"Error accessing Squid log file: {e}")
  349. except Exception as e:
  350. logger.error(f"Error checking Squid log health: {e}")
  351. def check_system_health():
  352. """Checks general system health"""
  353. try:
  354. # Check disk usage
  355. disk_usage = os.statvfs("/")
  356. free_disk_gb = (disk_usage.f_bavail * disk_usage.f_frsize) / (1024**3)
  357. if free_disk_gb < DISK_CRITICAL_GB:
  358. add_notification(
  359. "error",
  360. f"Espacio en disco crítico: {free_disk_gb:.1f}GB libres",
  361. "fa-hdd",
  362. "system",
  363. )
  364. elif free_disk_gb < DISK_WARNING_GB:
  365. add_notification(
  366. "warning",
  367. f"Espacio en disco bajo: {free_disk_gb:.1f}GB libres",
  368. "fa-hdd",
  369. "system",
  370. )
  371. except OSError as e:
  372. logger.error(f"Error checking disk usage: {e}")
  373. except Exception as e:
  374. logger.error(f"Error checking system health: {e}")
  375. # Function for commits
  376. def has_remote_commits_with_messages(
  377. repo_path: str, branch: str = "main"
  378. ) -> tuple[bool, list[str]]:
  379. git_dir = os.path.join(repo_path, ".git")
  380. if not os.path.isdir(git_dir):
  381. logger.warning(f"Not a valid Git repository: {repo_path}")
  382. return False, []
  383. try:
  384. # Configurar proxy si existe la variable de entorno
  385. env = os.environ.copy()
  386. http_proxy = env.get("HTTP_PROXY", "")
  387. if http_proxy:
  388. env["http_proxy"] = http_proxy
  389. env["https_proxy"] = http_proxy
  390. subprocess.run(
  391. ["git", "fetch"],
  392. cwd=repo_path,
  393. check=True,
  394. stdout=subprocess.DEVNULL,
  395. stderr=subprocess.DEVNULL,
  396. env=env,
  397. )
  398. result = subprocess.run(
  399. [
  400. "git",
  401. "rev-list",
  402. "--left-right",
  403. "--count",
  404. f"origin/{branch}...{branch}",
  405. ],
  406. cwd=repo_path,
  407. capture_output=True,
  408. text=True,
  409. check=True,
  410. env=env,
  411. )
  412. ahead_behind = result.stdout.strip().split()
  413. remote_ahead = int(ahead_behind[0])
  414. if remote_ahead > 0:
  415. log_result = subprocess.run(
  416. ["git", "log", f"{branch}..origin/{branch}", "--pretty=format:%s"],
  417. cwd=repo_path,
  418. capture_output=True,
  419. text=True,
  420. check=True,
  421. env=env,
  422. )
  423. commit_messages = (
  424. log_result.stdout.strip().split("\n")
  425. if log_result.stdout.strip()
  426. else []
  427. )
  428. return True, commit_messages
  429. return False, []
  430. except subprocess.CalledProcessError as e:
  431. logger.error(f"Error executing git commands: {e.stderr}")
  432. return False, []
  433. except Exception as e:
  434. logger.error(f"Unexpected error checking git commits: {e}")
  435. return False, []
  436. # Thread for periodic checks
  437. def start_notification_monitor():
  438. """Starts the notification monitor in background with graceful shutdown support"""
  439. global _monitor_stop_event, _monitor_thread
  440. _monitor_stop_event = threading.Event()
  441. def monitor_loop():
  442. check_count = 0
  443. cycle_interval = 60 # 1 minute between cycles for better granularity
  444. logger.info("Notification monitor started")
  445. while not _monitor_stop_event.is_set():
  446. try:
  447. # Check commits every N minutes
  448. if check_count % CHECK_COMMITS_INTERVAL == 0:
  449. current_file_dir = os.path.dirname(os.path.abspath(__file__))
  450. repo_path = os.path.dirname(current_file_dir)
  451. if os.path.exists(os.path.join(repo_path, ".git")):
  452. has_updates, messages = has_remote_commits_with_messages(
  453. repo_path
  454. )
  455. set_commit_notifications(has_updates, messages)
  456. # System health checks at different intervals
  457. if check_count % CHECK_SYSTEM_INTERVAL == 0:
  458. check_system_health()
  459. if check_count % CHECK_SQUID_LOG_INTERVAL == 0:
  460. check_squid_log_health()
  461. if check_count % CHECK_SECURITY_INTERVAL == 0:
  462. check_security_events()
  463. if check_count % CHECK_USER_ACTIVITY_INTERVAL == 0:
  464. check_user_activity()
  465. check_count = (check_count + 1) % 1000 # Reset to prevent overflow
  466. except Exception as e:
  467. logger.error(f"Error in notification monitor: {e}", exc_info=True)
  468. _monitor_stop_event.wait(timeout=cycle_interval)
  469. _monitor_thread = threading.Thread(
  470. target=monitor_loop, daemon=True, name="NotificationMonitor"
  471. )
  472. _monitor_thread.start()
  473. return _monitor_stop_event # Return the event for potential external control
  474. # Specific functions for Squid that can be called from other parts
  475. def notify_squid_restart_success():
  476. """Notify successful Squid restart"""
  477. add_notification("success", "Squid reiniciado exitosamente", "fa-sync-alt", "squid")
  478. def notify_squid_restart_failed(error_message: str = ""):
  479. """Notify failed Squid restart"""
  480. message = "Error al reiniciar Squid"
  481. if error_message:
  482. message += f": {error_message}"
  483. add_notification("error", message, "fa-exclamation-triangle", "squid")
  484. def notify_squid_config_error(error_message: str):
  485. """Notify Squid configuration error"""
  486. add_notification(
  487. "error", f"Error de configuración de Squid: {error_message}", "fa-cog", "squid"
  488. )
  489. def notify_squid_high_usage(warning_message: str):
  490. """Notify high Squid resource usage"""
  491. add_notification("warning", warning_message, "fa-chart-line", "squid")
  492. def check_security_events():
  493. """Checks security events from the database"""
  494. try:
  495. from services.analytics.auditoria_service import (
  496. # find_suspicious_activity,
  497. get_denied_requests,
  498. get_failed_auth_attempts,
  499. )
  500. with get_db_session() as db:
  501. # 1. Failed authentication attempts
  502. failed_auth_count = get_failed_auth_attempts(db, hours=1)
  503. if failed_auth_count > FAILED_AUTH_THRESHOLD:
  504. add_notification(
  505. "warning",
  506. f"{failed_auth_count} intentos de autenticación fallidos en la última hora",
  507. "fa-shield-alt",
  508. "security",
  509. )
  510. # 2. Denied requests
  511. denied_count = get_denied_requests(db, hours=1)
  512. if denied_count > DENIED_REQUESTS_THRESHOLD:
  513. add_notification(
  514. "warning",
  515. f"{denied_count} solicitudes denegadas en la última hora",
  516. "fa-ban",
  517. "security",
  518. )
  519. # # 3. Suspicious IPs (many requests in short time)
  520. # suspicious_ips = find_suspicious_activity(db, threshold=100, hours=1)
  521. #
  522. # if not suspicious_ips:
  523. # return
  524. #
  525. # # Limitar cantidad de notificaciones y ordenar por severidad
  526. # reported_count = 0
  527. # for ip, count in suspicious_ips:
  528. # if reported_count >= MAX_IPS_TO_REPORT:
  529. # # Si hay más IPs, notificar con resumen
  530. # remaining = len(suspicious_ips) - MAX_IPS_TO_REPORT
  531. # add_notification(
  532. # "info",
  533. # f"Hay {remaining} IP(s) adicionales con actividad sospechosa",
  534. # "fa-info-circle",
  535. # "security",
  536. # )
  537. # break
  538. #
  539. # # Verificar nivel crítico primero
  540. # if count > CRITICAL_IP_THRESHOLD:
  541. # add_notification(
  542. # "error",
  543. # f"Actividad crítica desde IP {ip}: {count:,} solicitudes/hora",
  544. # "fa-exclamation-triangle",
  545. # "security",
  546. # )
  547. # reported_count += 1
  548. # elif count > SUSPICIOUS_IP_THRESHOLD:
  549. # add_notification(
  550. # "warning",
  551. # f"Actividad sospechosa desde IP {ip}: {count:,} solicitudes/hora",
  552. # "fa-user-secret",
  553. # "security",
  554. # )
  555. # reported_count += 1
  556. except ImportError as e:
  557. logger.error(f"Error importing auditoria_service modules: {e}")
  558. except Exception as e:
  559. logger.error(f"Error checking security events: {e}", exc_info=True)
  560. def check_user_activity():
  561. """Checks user activity from the database"""
  562. try:
  563. from services.analytics.auditoria_service import (
  564. get_active_users_count,
  565. get_high_usage_users,
  566. )
  567. with get_db_session() as db:
  568. # 1. Active users in the last hour
  569. active_users = get_active_users_count(db, hours=1)
  570. if active_users > HIGH_ACTIVITY_THRESHOLD:
  571. add_notification(
  572. "info",
  573. f"Alta actividad: {active_users} usuarios conectados en la última hora",
  574. "fa-users",
  575. "users",
  576. )
  577. elif active_users == 0:
  578. add_notification(
  579. "warning",
  580. "No hay usuarios activos en la última hora",
  581. "fa-users",
  582. "users",
  583. )
  584. # 2. Users with high data consumption
  585. high_usage_users = get_high_usage_users(db, hours=24, threshold_mb=100)
  586. # Limitar a top N usuarios
  587. high_usage_gb = HIGH_USAGE_GB_THRESHOLD * 1024
  588. for user, usage_mb in high_usage_users[:MAX_USERS_TO_REPORT]:
  589. # Solo notificar si supera el umbral alto
  590. if usage_mb > high_usage_gb:
  591. add_notification(
  592. "warning",
  593. f"El usuario {user} consumió {usage_mb:,.0f}MB en 24h",
  594. "fa-chart-line",
  595. "users",
  596. )
  597. except ImportError as e:
  598. logger.error(f"Error importing auditoria_service modules: {e}")
  599. except Exception as e:
  600. logger.error(f"Error checking user activity: {e}", exc_info=True)