feat: add 'log_structured_entry' for JSON structured logs
Move config into own file
This commit is contained in:
50
utils/logging_setup.py
Normal file
50
utils/logging_setup.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
Centralized Cloud Logging setup.
|
||||
Uses CloudLoggingHandler (background thread) so logging does not add latency
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Optional, Dict, Literal
|
||||
|
||||
import google.cloud.logging
|
||||
from google.cloud.logging.handlers import CloudLoggingHandler
|
||||
|
||||
from .config import Settings
|
||||
|
||||
|
||||
def _setup_logger() -> logging.Logger:
|
||||
"""Create or return the singleton evaluation logger."""
|
||||
log_name = "va_agent-evaluation-logs"
|
||||
logger = logging.getLogger(log_name)
|
||||
cfg = Settings.model_validate({})
|
||||
if any(isinstance(h, CloudLoggingHandler) for h in logger.handlers):
|
||||
return logger
|
||||
|
||||
try:
|
||||
client = google.cloud.logging.Client(project=cfg.project_id)
|
||||
handler = CloudLoggingHandler(client, name=log_name) # async transport
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
except Exception as e:
|
||||
# Fallback to console if Cloud Logging is unavailable (local dev)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(log_name)
|
||||
logger.warning("Cloud Logging setup failed; using console. Error: %s", e)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
_eval_log = _setup_logger()
|
||||
|
||||
|
||||
def log_structured_entry(message: str, severity: Literal["INFO", "WARNING", "ERROR"], custom_log: Optional[Dict] = None) -> None:
|
||||
"""
|
||||
Emit a JSON-structured log row.
|
||||
|
||||
Args:
|
||||
message: Short label for the row (e.g., "Final agent turn").
|
||||
severity: "INFO" | "WARNING" | "ERROR" etc.
|
||||
custom_log: A dict with your structured payload.
|
||||
"""
|
||||
level = getattr(logging, severity.upper(), logging.INFO)
|
||||
_eval_log.log(level, message, extra={"json_fields": {"message": message, "custom": custom_log or {}}})
|
||||
Reference in New Issue
Block a user