|
5 | 5 | from enum import Enum |
6 | 6 | from typing import Annotated |
7 | 7 |
|
| 8 | +import logfire |
8 | 9 | from azure.cosmos.aio import CosmosClient |
9 | 10 | from azure.identity.aio import DefaultAzureCredential, ManagedIdentityCredential |
| 11 | +from azure.monitor.opentelemetry import configure_azure_monitor |
| 12 | +from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter |
10 | 13 | from dotenv import load_dotenv |
11 | 14 | from fastmcp import FastMCP |
| 15 | +from opentelemetry import trace |
| 16 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
12 | 17 |
|
13 | | -load_dotenv(override=True) |
| 18 | +RUNNING_IN_PRODUCTION = os.getenv("RUNNING_IN_PRODUCTION", "false").lower() == "true" |
| 19 | + |
| 20 | +if not RUNNING_IN_PRODUCTION: |
| 21 | + load_dotenv(override=True) |
14 | 22 |
|
15 | | -logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s") |
| 23 | +logging.basicConfig(level=logging.WARNING, format="%(asctime)s - %(message)s") |
16 | 24 | logger = logging.getLogger("ExpensesMCP") |
| 25 | +logger.setLevel(logging.INFO) |
| 26 | + |
| 27 | +# Configure OpenTelemetry tracing |
| 28 | +APPLICATIONINSIGHTS_CONNECTION_STRING = os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING") |
| 29 | +if APPLICATIONINSIGHTS_CONNECTION_STRING: |
| 30 | + logger.info("Setting up Azure Monitor instrumentation") |
| 31 | + configure_azure_monitor() |
| 32 | + |
| 33 | +# Use Logfire to instrument MCP tool calls |
| 34 | +logfire.configure( |
| 35 | + service_name="expenses-mcp", |
| 36 | + send_to_logfire=False, # Send spans to Application Insights, not Logfire backend |
| 37 | +) |
| 38 | +logfire.instrument_mcp() |
| 39 | + |
| 40 | +if APPLICATIONINSIGHTS_CONNECTION_STRING: |
| 41 | + logger.info("Adding Azure Monitor Trace Exporter to TracerProvider") |
| 42 | + tracer_provider = trace.get_tracer_provider() |
| 43 | + exporter = AzureMonitorTraceExporter(connection_string=APPLICATIONINSIGHTS_CONNECTION_STRING) |
| 44 | + span_processor = BatchSpanProcessor(exporter) |
| 45 | + tracer_provider.add_span_processor(span_processor) |
17 | 46 |
|
18 | 47 | # Cosmos DB configuration from environment variables |
19 | 48 | AZURE_COSMOSDB_ACCOUNT = os.environ["AZURE_COSMOSDB_ACCOUNT"] |
20 | 49 | AZURE_COSMOSDB_DATABASE = os.environ["AZURE_COSMOSDB_DATABASE"] |
21 | 50 | AZURE_COSMOSDB_CONTAINER = os.environ["AZURE_COSMOSDB_CONTAINER"] |
22 | | -RUNNING_IN_PRODUCTION = os.getenv("RUNNING_IN_PRODUCTION", "false").lower() == "true" |
23 | 51 | AZURE_CLIENT_ID = os.getenv("AZURE_CLIENT_ID", "") |
24 | 52 |
|
25 | 53 | # Configure Cosmos DB client and container |
|
0 commit comments