Spaces:
Paused

File size: 3,579 Bytes
5eb4857
 
 
 
 
7f2d326
 
5eb4857
 
 
7f2d326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
ce8fa6c
 
5eb4857
ab8d6bc
 
 
f3f25ca
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3f25ca
 
 
 
 
5eb4857
 
 
ff97dfb
 
 
 
5eb4857
ff97dfb
5eb4857
 
 
 
 
 
 
 
 
 
f3f25ca
 
 
 
 
5eb4857
 
 
f3f25ca
 
 
 
 
5eb4857
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import logging
import sys
from pathlib import Path
from logging.handlers import TimedRotatingFileHandler
from core.config import get_settings
import asyncio
from typing import Coroutine

settings = get_settings()

def safe_create_task(coro: Coroutine, name: str = "background_task") -> asyncio.Task:
    """
    Fire-and-forget an async task with automatic error logging.
    Prevents silent failures in un-awaited tasks.
    """
    task = asyncio.create_task(coro)
    
    def handle_result(t: asyncio.Task):
        try:
            t.result()
        except asyncio.CancelledError:
            pass
        except Exception as e:
            logging.getLogger("safe_task").error(f"❌ Background task '{name}' failed: {str(e)}", exc_info=True)
            
    task.add_done_callback(handle_result)
    return task

# Ensure logs directory exists
LOGS_DIR = Path(settings.effective_log_dir)
LOGS_DIR.mkdir(parents=True, exist_ok=True)

# Standard logging format used by all handlers
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

# Filter to suppress frequent health check logs in production to stay within cloud log quotas
class HealthCheckFilter(logging.Filter):
    def filter(self, record):
        return "/health" not in record.getMessage()

def setup_logging():
    """
    Configure global logging settings for the application.
    """
    log_level = logging.DEBUG if settings.DEBUG else logging.INFO
    
    # Root logger configuration
    root_logger = logging.getLogger()
    root_logger.setLevel(log_level)
    
    # Remove existing handlers to avoid duplicates
    if root_logger.hasHandlers():
        root_logger.handlers.clear()
        
    # 1. Console Handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(logging.Formatter(LOG_FORMAT))
    
    # Add health check filter to console handler if not in DEBUG
    if not settings.DEBUG:
        console_handler.addFilter(HealthCheckFilter())
        
    root_logger.addHandler(console_handler)
    
    # 2. File Handler (Timed Rotating - Daily)
    # We include the PID in the filename in production to prevent race conditions
    # when multiple workers attempt to rotate the same file at midnight.
    import os
    log_filename = "app.log" if settings.DEBUG else f"app.{os.getpid()}.log"
    file_handler = TimedRotatingFileHandler(
        LOGS_DIR / log_filename,
        when="midnight",
        interval=1,
        backupCount=30,  # Keep 30 days of logs
        encoding="utf-8"
    )
    file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
    root_logger.addHandler(file_handler)
    
    # 3. Suppress noisy third-party libraries if not in DEBUG
    if not settings.DEBUG:
        # Keep uvicorn.access at INFO but the filter will catch /health noise
        logging.getLogger("uvicorn.access").setLevel(logging.INFO)
        logging.getLogger("uvicorn.access").addFilter(HealthCheckFilter())
        
        # Suppress heavy debug noise from core libraries
        logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
        logging.getLogger("httpx").setLevel(logging.WARNING)
        logging.getLogger("langchain_ollama").setLevel(logging.INFO)
        logging.getLogger("arq").setLevel(logging.INFO)
        
        # Prevent double logging
        logging.getLogger("uvicorn.access").propagate = False
        logging.getLogger("uvicorn.error").propagate = False

def get_logger(name: str):
    """
    Utility to get a logger instance for a specific module.
    """
    return logging.getLogger(name)