"""Google Cloud Platform log formatter."""
import os
from typing import Any, ClassVar
__all__ = ("GCPLogFormatter",)
class GCPLogFormatter:
"""Formatter for Google Cloud Logging structured format.
Produces JSON-compatible dictionaries that conform to GCP's
structured logging format, including:
- severity field with GCP severity levels
- logging.googleapis.com/trace for trace correlation
- logging.googleapis.com/spanId for span tracking
- logging.googleapis.com/labels for custom labels
- logging.googleapis.com/sourceLocation for code location
Reference:
https://cloud.google.com/logging/docs/structured-logging
"""
__slots__ = ("_project_id",)
SEVERITY_MAP: ClassVar[dict[str, str]] = {
"DEBUG": "DEBUG",
"INFO": "INFO",
"WARNING": "WARNING",
"ERROR": "ERROR",
"CRITICAL": "CRITICAL",
}
def __init__(self, project_id: str | None = None) -> None:
"""Initialize GCP log formatter.
Args:
project_id: GCP project ID for trace URL construction.
If not provided, attempts to read from GOOGLE_CLOUD_PROJECT
environment variable.
"""
self._project_id = project_id or os.environ.get("GOOGLE_CLOUD_PROJECT")