Spaces:
Sleeping
Sleeping
Download app/utils/logging_utils.py from maddy1007/shl-recommender: direct link, hf CLI and curl.
- Browser
- Download file 1.78 kB
-
https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/app/utils/logging_utils.py
- Command line
-
hf download hf://spaces/maddy1007/shl-recommender/app/utils/logging_utils.py
-
curl -L -o logging_utils.py https://huggingface.co/spaces/maddy1007/shl-recommender/resolve/main/app/utils/logging_utils.py
1.78 kB
| """ | |
| Structured logging utilities. | |
| Wraps Python's standard logging with consistent JSON-friendly formatting | |
| and structured context helpers used throughout the application. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import os | |
| import time | |
| from contextlib import contextmanager | |
| from typing import Generator | |
| def get_logger(name: str) -> logging.Logger: | |
| """ | |
| Return a named logger with level set from LOG_LEVEL env var. | |
| Use this instead of logging.getLogger() directly. | |
| """ | |
| logger = logging.getLogger(name) | |
| level = os.getenv("LOG_LEVEL", "INFO").upper() | |
| logger.setLevel(getattr(logging, level, logging.INFO)) | |
| return logger | |
| def log_latency( | |
| logger: logging.Logger, | |
| operation: str, | |
| threshold_ms: float = 5000.0, | |
| ) -> Generator[None, None, None]: | |
| """ | |
| Context manager that logs the duration of a block. | |
| Emits a WARNING if the operation exceeds `threshold_ms`. | |
| Usage:: | |
| with log_latency(logger, "vector_search"): | |
| results = index.search(query) | |
| """ | |
| t0 = time.perf_counter() | |
| try: | |
| yield | |
| finally: | |
| elapsed_ms = (time.perf_counter() - t0) * 1000 | |
| level = logging.WARNING if elapsed_ms > threshold_ms else logging.DEBUG | |
| logger.log( | |
| level, | |
| "%s completed in %.1fms%s", | |
| operation, | |
| elapsed_ms, | |
| " ⚠ SLOW" if elapsed_ms > threshold_ms else "", | |
| ) | |
| def sanitize_for_log(text: str, max_chars: int = 120) -> str: | |
| """ | |
| Truncate and strip newlines from text before logging. | |
| Prevents log pollution from long JDs or LLM outputs. | |
| """ | |
| safe = text.replace("\n", " ").replace("\r", "") | |
| if len(safe) > max_chars: | |
| return safe[:max_chars] + "…" | |
| return safe | |