Spaces:
Running

File size: 7,446 Bytes
567eb03
90531db
 
 
567eb03
 
 
90531db
 
 
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
 
54559aa
567eb03
 
54559aa
567eb03
 
54559aa
567eb03
 
 
 
 
 
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
54559aa
567eb03
 
54559aa
567eb03
 
54559aa
567eb03
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54559aa
567eb03
 
 
 
 
 
 
54559aa
567eb03
 
 
 
 
 
 
 
 
 
 
 
 
90531db
 
 
567eb03
90531db
 
 
 
 
 
 
 
 
567eb03
 
 
90531db
567eb03
90531db
 
 
 
 
 
 
 
 
567eb03
90531db
 
 
567eb03
90531db
 
567eb03
90531db
567eb03
 
90531db
 
 
567eb03
 
 
 
 
 
 
 
 
90531db
567eb03
 
 
 
 
54559aa
567eb03
 
54559aa
567eb03
 
 
 
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""Enhanced logging configuration for the application."""

import logging
import sys
import time
import uuid
from contextvars import ContextVar

from src.config import settings

# Context variable for request ID tracking
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")


class RequestIdFilter(logging.Filter):
    """Add request ID to log records for request tracing."""

    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = request_id_var.get("-")
        return True


class DetailedFormatter(logging.Formatter):
    """
    Enhanced formatter with colors and structured output for development.

    Includes: timestamp, level, module, function, line number, request ID, and message.
    """

    # ANSI color codes
    COLORS = {
        "DEBUG": "\033[36m",     # Cyan
        "INFO": "\033[32m",      # Green
        "WARNING": "\033[33m",   # Yellow
        "ERROR": "\033[31m",     # Red
        "CRITICAL": "\033[35m",  # Magenta
    }
    RESET = "\033[0m"
    BOLD = "\033[1m"
    DIM = "\033[2m"

    def __init__(self, use_colors: bool = True):
        super().__init__()
        self.use_colors = use_colors

    def format(self, record: logging.LogRecord) -> str:
        # Get request ID (default to "-" if not set)
        request_id = getattr(record, "request_id", "-")

        # Format timestamp
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created))
        milliseconds = int((record.created % 1) * 1000)

        # Get level color
        level_color = self.COLORS.get(record.levelname, "")

        # Format location (module:function:line)
        location = f"{record.module}.{record.funcName}:{record.lineno}"

        if self.use_colors:
            # Colored output for terminal
            level_str = f"{level_color}{self.BOLD}{record.levelname:8}{self.RESET}"
            timestamp_str = f"{self.DIM}{timestamp}.{milliseconds:03d}{self.RESET}"
            location_str = f"{self.DIM}{location}{self.RESET}"
            request_id_str = f"[{request_id[:8]}]" if request_id != "-" else ""

            return f"{timestamp_str} {level_str} {location_str} {request_id_str} {record.getMessage()}"
        else:
            # Plain text for file logging
            request_id_str = f"[{request_id}]" if request_id != "-" else ""
            return f"{timestamp}.{milliseconds:03d} | {record.levelname:8} | {location:40} | {request_id_str} {record.getMessage()}"


class APILogFormatter(logging.Formatter):
    """Structured formatter for API request/response logging."""

    def format(self, record: logging.LogRecord) -> str:
        # Check if this is an API log with extra data
        if hasattr(record, "api_data"):
            data = record.api_data
            parts = [
                f"[{data.get('provider', 'UNKNOWN')}]",
                f"{data.get('method', '')} {data.get('endpoint', '')}",
            ]

            if "status_code" in data:
                parts.append(f"-> {data['status_code']}")

            if "duration_ms" in data:
                parts.append(f"({data['duration_ms']:.0f}ms)")

            if "error" in data:
                parts.append(f"ERROR: {data['error']}")

            return " ".join(parts)

        return super().format(record)


def get_request_id() -> str:
    """Get the current request ID from context."""
    return request_id_var.get("-")


def set_request_id(request_id: str | None = None) -> str:
    """
    Set a request ID for the current context.

    Args:
        request_id: Optional request ID (generates UUID if not provided)

    Returns:
        The request ID that was set
    """
    if request_id is None:
        request_id = str(uuid.uuid4())
    request_id_var.set(request_id)
    return request_id


def log_api_call(
    logger: logging.Logger,
    provider: str,
    method: str,
    endpoint: str,
    status_code: int | None = None,
    duration_ms: float | None = None,
    error: str | None = None,
    level: int = logging.DEBUG,
) -> None:
    """
    Log an API call with structured data.

    Args:
        logger: Logger instance
        provider: API provider name (e.g., "ThreatFox", "VirusTotal")
        method: HTTP method
        endpoint: API endpoint
        status_code: Response status code
        duration_ms: Request duration in milliseconds
        error: Error message if request failed
        level: Log level
    """
    api_data = {
        "provider": provider,
        "method": method,
        "endpoint": endpoint,
    }

    if status_code is not None:
        api_data["status_code"] = status_code
    if duration_ms is not None:
        api_data["duration_ms"] = duration_ms
    if error is not None:
        api_data["error"] = error
        level = logging.ERROR

    # Create log record with extra data
    record = logger.makeRecord(
        logger.name,
        level,
        "",
        0,
        f"[{provider}] {method} {endpoint}" + (f" -> {status_code}" if status_code else "") + (f" ({duration_ms:.0f}ms)" if duration_ms else "") + (f" ERROR: {error}" if error else ""),
        (),
        None,
    )
    record.api_data = api_data
    logger.handle(record)


def setup_logging(log_level: str | None = None) -> None:
    """
    Configure application-wide logging with enhanced detail.

    Args:
        log_level: Optional log level override (defaults to settings.LOG_LEVEL)
    """
    log_level = log_level or settings.LOG_LEVEL

    # Convert string to logging level
    numeric_level = getattr(logging, log_level.upper(), logging.INFO)

    # Check if we're in a TTY (terminal) for color support
    use_colors = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()

    # Create formatter
    formatter = DetailedFormatter(use_colors=use_colors)

    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(numeric_level)

    # Remove existing handlers
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)

    # Console handler with detailed formatting
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(numeric_level)
    console_handler.setFormatter(formatter)
    console_handler.addFilter(RequestIdFilter())
    root_logger.addHandler(console_handler)

    # Set logging level for third-party libraries (reduce noise)
    logging.getLogger("uvicorn").setLevel(logging.INFO)
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    logging.getLogger("uvicorn.error").setLevel(logging.INFO)
    logging.getLogger("fastapi").setLevel(logging.INFO)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)

    # Application loggers at debug level when in DEBUG mode
    if numeric_level == logging.DEBUG:
        logging.getLogger("src").setLevel(logging.DEBUG)
        logging.getLogger("src.services").setLevel(logging.DEBUG)
        logging.getLogger("src.api").setLevel(logging.DEBUG)

    logging.info(f"Logging configured: level={log_level}, colors={use_colors}")


# Convenience logger creation
def get_logger(name: str) -> logging.Logger:
    """
    Get a logger with the application's configuration.

    Args:
        name: Logger name (usually __name__)

    Returns:
        Configured logger instance
    """
    return logging.getLogger(name)