import os import sys import logging # Принудительный вывод в консоль, чтобы видеть, где происходит затык print("DEBUG: Starting telemetry setup...", flush=True) from opentelemetry import trace, metrics from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter print("DEBUG: Core OTel imports successful", flush=True) def setup_telemetry(): print("DEBUG: Inside setup_telemetry()", flush=True) service_name = os.getenv("OTEL_SERVICE_NAME", "messenger") resource = Resource.create({ "service.name": service_name, "service.version": os.getenv("OTEL_SERVICE_VERSION", "1.0.0"), "deployment.environment": os.getenv("OTEL_ENVIRONMENT", "lab") }) otlp_endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318") print(f"DEBUG: Exporting to {otlp_endpoint}", flush=True) # 1. Tracing trace.set_tracer_provider(TracerProvider(resource=resource)) span_exporter = OTLPSpanExporter(endpoint=f"{otlp_endpoint}/v1/traces") trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(span_exporter)) print("DEBUG: Tracing setup complete", flush=True) # 2. Metrics metric_reader = PeriodicExportingMetricReader( OTLPMetricExporter(endpoint=f"{otlp_endpoint}/v1/metrics"), export_interval_millis=10000 ) metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[metric_reader])) print("DEBUG: Metrics setup complete", flush=True) # 3. Инструментация библиотек (импортируем здесь, чтобы избежать проблем с порядком загрузки) from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor from opentelemetry.instrumentation.logging import LoggingInstrumentor FastAPIInstrumentor().instrument() print("DEBUG: FastAPI instrumented", flush=True) AsyncPGInstrumentor().instrument() print("DEBUG: AsyncPG instrumented", flush=True) AioPikaInstrumentor().instrument() print("DEBUG: AioPika instrumented", flush=True) # Интеграция с logging (добавляет trace_id и span_id в логи) LoggingInstrumentor().instrument(set_logging_format=True) print("DEBUG: Logging instrumented", flush=True) # Базовая настройка логгера (не переопределяем uvicorn агрессивно) logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] [%(name)s] %(message)s") logging.getLogger(__name__).info(f"OpenTelemetry fully initialized for {service_name}") print("DEBUG: Telemetry setup COMPLETE", flush=True)