Download src/core/observability/setup.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/observability/setup.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/observability/setup.py
-
curl -L -o setup.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/observability/setup.py
13.6 kB
| """ | |
| YAZ Platform — Unified Observability Setup | |
| ========================================== | |
| Single function ``configure_observability(app)`` to call once at startup. | |
| Wires together: | |
| • OpenTelemetry (OTLP exporter → Grafana Cloud / local collector) | |
| • Prometheus (``/metrics`` endpoint + FastAPI middleware counters) | |
| • loguru (JSON in production, human-readable in development) | |
| • Sentry SDK (error tracking + performance traces) | |
| Usage (src/main.py or app factory) | |
| ----------------------------------- | |
| from src.core.observability.setup import configure_observability | |
| app = FastAPI(...) | |
| configure_observability(app) | |
| Environment variables read | |
| -------------------------- | |
| YAZ_ENV development | testing | production | |
| OTEL_EXPORTER_OTLP_ENDPOINT e.g. https://otlp.grafana.net:4318 | |
| OTEL_EXPORTER_OTLP_HEADERS e.g. Authorization=Basic <token> | |
| OTEL_SERVICE_NAME default: yaz-care | |
| SENTRY_DSN Sentry ingestion URL (optional) | |
| LOG_LEVEL DEBUG | INFO | WARNING | ERROR | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import os | |
| import sys | |
| import time | |
| from typing import TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from fastapi import FastAPI | |
| logger = logging.getLogger(__name__) | |
| # ── Loguru ───────────────────────────────────────────────────────────────────── | |
| def _configure_loguru(log_level: str = "INFO", json_logs: bool = True) -> None: | |
| """ | |
| Replace stdlib root logger with loguru. | |
| In production: newline-delimited JSON (compatible with Loki / Cloud Logging). | |
| In development: colourful human-readable format. | |
| """ | |
| try: | |
| from loguru import logger as _loguru | |
| # Remove default loguru handler | |
| _loguru.remove() | |
| if json_logs: | |
| def _json_sink(message: object) -> None: | |
| record = message.record # type: ignore[attr-defined, union-attr] | |
| payload = { | |
| "ts": record["time"].isoformat(), | |
| "level": record["level"].name, | |
| "logger": record["name"], | |
| "msg": record["message"], | |
| "module": record["module"], | |
| "line": record["line"], | |
| } | |
| if record["exception"]: | |
| payload["exc"] = str(record["exception"]) | |
| if record["extra"]: | |
| payload["extra"] = { | |
| k: v | |
| for k, v in record["extra"].items() | |
| # Skip PHI-tagged values from log output | |
| if k not in {"patient_name", "ssn", "dob", "phi"} | |
| } | |
| sys.stdout.write(json.dumps(payload) + "\n") | |
| sys.stdout.flush() | |
| _loguru.add(_json_sink, level=log_level, enqueue=True) | |
| else: | |
| _loguru.add( | |
| sys.stdout, | |
| level=log_level, | |
| format=( | |
| "<green>{time:HH:mm:ss}</green> | " | |
| "<level>{level: <8}</level> | " | |
| "<cyan>{name}</cyan>:<cyan>{line}</cyan> — {message}" | |
| ), | |
| colorize=True, | |
| enqueue=True, | |
| ) | |
| # Bridge stdlib → loguru so third-party libs appear in the same stream | |
| class _InterceptHandler(logging.Handler): | |
| def emit(self, record: logging.LogRecord) -> None: | |
| try: | |
| level = _loguru.level(record.levelname).name | |
| except ValueError: | |
| level = str(record.levelno) | |
| frame, depth = sys._getframe(6), 6 | |
| while frame and frame.f_code.co_filename == logging.__file__: | |
| frame = frame.f_back # type: ignore[assignment] | |
| depth += 1 | |
| _loguru.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) | |
| logging.basicConfig(handlers=[_InterceptHandler()], level=0, force=True) | |
| logger.info("loguru configured (json=%s, level=%s)", json_logs, log_level) | |
| except ImportError: | |
| logging.basicConfig(level=log_level, stream=sys.stdout) | |
| logging.warning("loguru not installed — using stdlib logging") | |
| # ── OpenTelemetry ───────────────────────────────────────────────────────────── | |
| def _configure_otel( | |
| app: "FastAPI", | |
| service_name: str, | |
| otlp_endpoint: str, | |
| otlp_headers: str, | |
| ) -> None: | |
| """ | |
| Instrument FastAPI, asyncpg, Redis, and httpx with OpenTelemetry. | |
| Exports via OTLP/HTTP to Grafana Cloud (or any OTLP-compatible backend). | |
| """ | |
| if not otlp_endpoint: | |
| logger.info("OTEL_EXPORTER_OTLP_ENDPOINT not set — tracing disabled") | |
| return | |
| try: | |
| from opentelemetry import trace | |
| from opentelemetry.sdk.resources import Resource, SERVICE_NAME | |
| from opentelemetry.sdk.trace import TracerProvider | |
| from opentelemetry.sdk.trace.export import BatchSpanProcessor | |
| from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( | |
| OTLPSpanExporter, | |
| ) | |
| from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor | |
| from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor | |
| from opentelemetry.instrumentation.redis import RedisInstrumentor | |
| from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor | |
| resource = Resource.create({SERVICE_NAME: service_name}) | |
| provider = TracerProvider(resource=resource) | |
| headers: dict[str, str] = {} | |
| if otlp_headers: | |
| for pair in otlp_headers.split(","): | |
| pair = pair.strip() | |
| if "=" in pair: | |
| k, _, v = pair.partition("=") | |
| headers[k.strip()] = v.strip() | |
| exporter = OTLPSpanExporter(endpoint=otlp_endpoint, headers=headers) | |
| provider.add_span_processor(BatchSpanProcessor(exporter)) | |
| trace.set_tracer_provider(provider) | |
| FastAPIInstrumentor.instrument_app(app) | |
| AsyncPGInstrumentor().instrument() | |
| RedisInstrumentor().instrument() | |
| HTTPXClientInstrumentor().instrument() | |
| logger.info( | |
| "OpenTelemetry initialised (service=%s, endpoint=%s)", | |
| service_name, | |
| otlp_endpoint, | |
| ) | |
| except ImportError as exc: | |
| logger.warning("OpenTelemetry packages missing (%s) — tracing disabled", exc) | |
| # ── Prometheus ──────────────────────────────────────────────────────────────── | |
| def _configure_prometheus(app: "FastAPI") -> None: | |
| """ | |
| Mount Prometheus /metrics endpoint and register HTTP request middleware. | |
| Reuses (and does NOT re-register) any counters already created by | |
| src.core.observability.monitoring.MetricsCollector. | |
| """ | |
| try: | |
| from prometheus_client import ( | |
| Counter, | |
| Histogram, | |
| generate_latest, | |
| CONTENT_TYPE_LATEST, | |
| REGISTRY, | |
| ) | |
| from fastapi import Request, Response | |
| from fastapi.routing import APIRoute | |
| # Only register if not already present (avoid duplicate registration) | |
| existing_names = {m.name for m in REGISTRY.collect()} | |
| if "yaz_http_requests_total" not in existing_names: | |
| request_counter = Counter( | |
| "yaz_http_requests_total", | |
| "Total HTTP requests", | |
| ["method", "path", "status"], | |
| ) | |
| else: | |
| request_counter = REGISTRY._names_to_collectors.get( | |
| "yaz_http_requests_total" | |
| ) # type: ignore[assignment] | |
| if "yaz_http_request_duration_seconds" not in existing_names: | |
| request_histogram = Histogram( | |
| "yaz_http_request_duration_seconds", | |
| "HTTP request latency in seconds", | |
| ["method", "path"], | |
| buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0], | |
| ) | |
| else: | |
| request_histogram = REGISTRY._names_to_collectors.get( | |
| "yaz_http_request_duration_seconds" | |
| ) # type: ignore[assignment] | |
| async def _prometheus_middleware(request: Request, call_next: object) -> Response: | |
| start = time.perf_counter() | |
| response: Response = await call_next(request) # type: ignore[operator] | |
| duration = time.perf_counter() - start | |
| # Normalise path to avoid high-cardinality (e.g. /cases/uuid → /cases/{id}) | |
| path = request.url.path | |
| for route in app.routes: | |
| if isinstance(route, APIRoute) and route.path_regex.match(path): | |
| path = route.path | |
| break | |
| if request_counter: | |
| request_counter.labels( | |
| method=request.method, | |
| path=path, | |
| status=response.status_code, | |
| ).inc() | |
| if request_histogram: | |
| request_histogram.labels(method=request.method, path=path).observe(duration) | |
| return response | |
| async def _metrics() -> Response: | |
| return Response( | |
| content=generate_latest(), | |
| media_type=CONTENT_TYPE_LATEST, | |
| ) | |
| logger.info("Prometheus /metrics endpoint registered") | |
| except ImportError as exc: | |
| logger.warning("prometheus_client missing (%s) — /metrics disabled", exc) | |
| # ── Sentry ──────────────────────────────────────────────────────────────────── | |
| def _configure_sentry(dsn: str, environment: str, release: str) -> None: | |
| """ | |
| Initialise Sentry SDK with FastAPI + SQLAlchemy integrations. | |
| No-op if SENTRY_DSN is empty. | |
| """ | |
| if not dsn: | |
| return | |
| try: | |
| import sentry_sdk | |
| from sentry_sdk.integrations.fastapi import FastApiIntegration | |
| from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration | |
| from sentry_sdk.integrations.logging import LoggingIntegration | |
| from sentry_sdk.integrations.redis import RedisIntegration | |
| sentry_sdk.init( | |
| dsn=dsn, | |
| environment=environment, | |
| release=release, | |
| traces_sample_rate=0.1 if environment == "production" else 1.0, | |
| profiles_sample_rate=0.05, | |
| integrations=[ | |
| FastApiIntegration(transaction_style="url"), | |
| SqlalchemyIntegration(), | |
| RedisIntegration(), | |
| LoggingIntegration(level=logging.WARNING, event_level=logging.ERROR), | |
| ], | |
| # Never send PHI to Sentry | |
| before_send=_sentry_scrub_phi, # type: ignore[arg-type, assignment] | |
| ) | |
| logger.info("Sentry initialised (env=%s)", environment) | |
| except ImportError as exc: | |
| logger.warning("sentry-sdk missing (%s) — error tracking disabled", exc) | |
| def _sentry_scrub_phi(event: dict, hint: object) -> dict | None: | |
| """ | |
| Strip known PHI fields from Sentry events before transmission. | |
| Returns None to drop the event entirely if it contains raw PHI. | |
| """ | |
| _phi_keys = {"patient_name", "ssn", "birth_date", "dob", "phone", "address"} | |
| def _scrub(obj: object) -> object: | |
| if isinstance(obj, dict): | |
| return { | |
| k: "[redacted]" if k.lower() in _phi_keys else _scrub(v) for k, v in obj.items() | |
| } | |
| if isinstance(obj, list): | |
| return [_scrub(item) for item in obj] | |
| return obj | |
| return _scrub(event) # type: ignore[return-value] | |
| # ── Public API ───────────────────────────────────────────────────────────────── | |
| def configure_observability(app: "FastAPI") -> None: | |
| """ | |
| One-call setup for the full observability stack. | |
| Call this once after ``FastAPI()`` is instantiated, before any routes are | |
| registered (so OTEL instrumentation wraps all endpoints). | |
| Args: | |
| app: The FastAPI application instance. | |
| """ | |
| env = os.getenv("YAZ_ENV", "production") | |
| is_prod = env == "production" | |
| log_level = os.getenv("LOG_LEVEL", "INFO").upper() | |
| _configure_loguru(log_level=log_level, json_logs=is_prod) | |
| _configure_otel( | |
| app=app, | |
| service_name=os.getenv("OTEL_SERVICE_NAME", "yaz-care"), | |
| otlp_endpoint=os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", ""), | |
| otlp_headers=os.getenv("OTEL_EXPORTER_OTLP_HEADERS", ""), | |
| ) | |
| _configure_prometheus(app) | |
| from src.__version__ import __version__ as _version # type: ignore[import] | |
| _configure_sentry( | |
| dsn=os.getenv("SENTRY_DSN", ""), | |
| environment=env, | |
| release=_version, | |
| ) | |
| logger.info("Observability stack configured (env=%s, log_level=%s)", env, log_level) | |