Skip to content

Commit b4cc949

Browse files
refactor: Clean up unused imports and whitespace in multiple files
1 parent 3233f1c commit b4cc949

5 files changed

Lines changed: 37 additions & 43 deletions

File tree

src/backend/api/api_routes.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
# Standard library
44
import asyncio
55
import io
6-
import logging
7-
import os
86
import zipfile
97
from typing import Optional
108

src/backend/api/event_utils.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
def _get_telemetry_client():
1818
"""Get or create the Application Insights telemetry client."""
1919
global _telemetry_client
20-
20+
2121
if _telemetry_client is None:
2222
connection_string = os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")
2323
if connection_string:
@@ -26,26 +26,26 @@ def _get_telemetry_client():
2626
# Format: InstrumentationKey=xxx;IngestionEndpoint=https://...
2727
parts = dict(part.split('=', 1) for part in connection_string.split(';') if '=' in part)
2828
instrumentation_key = parts.get('InstrumentationKey')
29-
29+
3030
if instrumentation_key:
3131
# Create a synchronous channel for immediate sending
3232
sender = SynchronousSender()
3333
queue = SynchronousQueue(sender)
3434
channel = TelemetryChannel(None, queue)
35-
35+
3636
_telemetry_client = TelemetryClient(instrumentation_key, channel)
3737
logging.info("Application Insights TelemetryClient initialized successfully")
3838
else:
3939
logging.error("Could not extract InstrumentationKey from connection string")
4040
except Exception as e:
4141
logging.error(f"Failed to initialize TelemetryClient: {e}")
42-
42+
4343
return _telemetry_client
4444

4545

4646
def track_event_if_configured(event_name: str, event_data: dict):
4747
"""Track a custom event to Application Insights customEvents table.
48-
48+
4949
This uses the Application Insights SDK TelemetryClient which properly
5050
sends custom events to the customEvents table in Application Insights.
5151
"""
@@ -56,11 +56,11 @@ def track_event_if_configured(event_name: str, event_data: dict):
5656
if client:
5757
# Convert all values to strings to ensure compatibility
5858
properties = {k: str(v) for k, v in event_data.items()}
59-
59+
6060
# Track the custom event
6161
client.track_event(event_name, properties=properties)
6262
client.flush() # Ensure immediate sending
63-
63+
6464
logging.debug(f"Tracked custom event: {event_name} with data: {event_data}")
6565
else:
6666
logging.warning("TelemetryClient not available, custom event not tracked")

src/backend/app.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
from api.api_routes import router as backend_router
77

8-
from azure.monitor.opentelemetry import configure_azure_monitor
98
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter, AzureMonitorTraceExporter
109

1110
from common.config.config import app_config
@@ -142,25 +141,25 @@ def create_app() -> FastAPI:
142141
# SOLUTION: Use manual telemetry setup instead of configure_azure_monitor
143142
# This gives us precise control over what gets instrumented, avoiding interference
144143
# with Semantic Kernel's async generators while still tracking Azure SDK calls
145-
144+
146145
# Set up Azure Monitor exporter for traces
147146
azure_trace_exporter = AzureMonitorTraceExporter(connection_string=instrumentation_key)
148-
147+
149148
# Create a tracer provider and add the Azure Monitor exporter
150149
tracer_provider = TracerProvider()
151150
tracer_provider.add_span_processor(BatchSpanProcessor(azure_trace_exporter))
152-
151+
153152
# Set the global tracer provider
154153
trace.set_tracer_provider(tracer_provider)
155154

156155
# Set up Azure Monitor exporter for logs (appears in traces table)
157156
azure_log_exporter = AzureMonitorLogExporter(connection_string=instrumentation_key)
158-
157+
159158
# Create a logger provider and add the Azure Monitor exporter
160159
logger_provider = LoggerProvider()
161160
logger_provider.add_log_record_processor(BatchLogRecordProcessor(azure_log_exporter))
162161
set_logger_provider(logger_provider)
163-
162+
164163
# Attach OpenTelemetry handler to Python's root logger
165164
handler = LoggingHandler(logger_provider=logger_provider)
166165
logging.getLogger().addHandler(handler)
@@ -172,13 +171,13 @@ def create_app() -> FastAPI:
172171
excluded_urls="socket,ws", # Exclude WebSocket URLs to reduce noise
173172
tracer_provider=tracer_provider
174173
)
175-
174+
176175
# Optional: Add manual spans in your code for Azure SDK operations using:
177176
# from opentelemetry import trace
178177
# tracer = trace.get_tracer(__name__)
179178
# with tracer.start_as_current_span("operation_name"):
180179
# # your Azure SDK call here
181-
180+
182181
logger.logger.info("Application Insights configured with selective instrumentation")
183182
logger.logger.info("✓ FastAPI HTTP tracing enabled")
184183
logger.logger.info("✓ Python logging export to Application Insights enabled")
@@ -188,7 +187,6 @@ def create_app() -> FastAPI:
188187
else:
189188
logger.logger.warning("No Application Insights connection string found. Telemetry disabled.")
190189

191-
192190
# Include routers with /api prefix
193191
app.include_router(backend_router, prefix="/api", tags=["backend"])
194192
# app.include_router(agents_router, prefix="/api/agents", tags=["agents"])

src/backend/common/telemetry/telemetry_helper.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,17 @@
66
77
Example usage:
88
from common.telemetry.telemetry_helper import trace_operation
9-
9+
1010
@trace_operation("cosmosdb_query")
1111
async def query_items(self, query: str):
1212
# Your CosmosDB query here
1313
pass
1414
"""
1515

16+
import asyncio
1617
import functools
1718
from contextlib import asynccontextmanager, contextmanager
18-
from typing import Any, Optional
19+
from typing import Optional
1920

2021
from opentelemetry import trace
2122
from opentelemetry.trace import Status, StatusCode
@@ -28,11 +29,11 @@ def get_tracer(name: str = __name__):
2829

2930
def trace_operation(operation_name: str, attributes: Optional[dict] = None):
3031
"""Decorator to add telemetry span to a function or method.
31-
32+
3233
Args:
3334
operation_name: Name of the operation for the span
3435
attributes: Optional dictionary of attributes to add to the span
35-
36+
3637
Example:
3738
@trace_operation("batch_processing", {"service": "sql_agents"})
3839
async def process_batch(batch_id: str):
@@ -48,10 +49,10 @@ async def async_wrapper(*args, **kwargs):
4849
if attributes:
4950
for key, value in attributes.items():
5051
span.set_attribute(key, str(value))
51-
52+
5253
# Add function arguments as attributes (optional, for debugging)
5354
span.set_attribute("function", func.__name__)
54-
55+
5556
try:
5657
result = await func(*args, **kwargs)
5758
span.set_status(Status(StatusCode.OK))
@@ -60,17 +61,17 @@ async def async_wrapper(*args, **kwargs):
6061
span.record_exception(e)
6162
span.set_status(Status(StatusCode.ERROR, str(e)))
6263
raise
63-
64+
6465
@functools.wraps(func)
6566
def sync_wrapper(*args, **kwargs):
6667
tracer = get_tracer(func.__module__)
6768
with tracer.start_as_current_span(operation_name) as span:
6869
if attributes:
6970
for key, value in attributes.items():
7071
span.set_attribute(key, str(value))
71-
72+
7273
span.set_attribute("function", func.__name__)
73-
74+
7475
try:
7576
result = func(*args, **kwargs)
7677
span.set_status(Status(StatusCode.OK))
@@ -79,24 +80,24 @@ def sync_wrapper(*args, **kwargs):
7980
span.record_exception(e)
8081
span.set_status(Status(StatusCode.ERROR, str(e)))
8182
raise
82-
83+
8384
# Return appropriate wrapper based on function type
8485
if asyncio.iscoroutinefunction(func):
8586
return async_wrapper
8687
else:
8788
return sync_wrapper
88-
89+
8990
return decorator
9091

9192

9293
@asynccontextmanager
9394
async def trace_context(operation_name: str, attributes: Optional[dict] = None):
9495
"""Async context manager for adding telemetry span to a code block.
95-
96+
9697
Args:
9798
operation_name: Name of the operation for the span
9899
attributes: Optional dictionary of attributes to add to the span
99-
100+
100101
Example:
101102
async with trace_context("cosmosdb_batch_query", {"batch_id": batch_id}):
102103
results = await database.query_items(query)
@@ -107,7 +108,7 @@ async def trace_context(operation_name: str, attributes: Optional[dict] = None):
107108
if attributes:
108109
for key, value in attributes.items():
109110
span.set_attribute(key, str(value))
110-
111+
111112
try:
112113
yield span
113114
span.set_status(Status(StatusCode.OK))
@@ -120,11 +121,11 @@ async def trace_context(operation_name: str, attributes: Optional[dict] = None):
120121
@contextmanager
121122
def trace_sync_context(operation_name: str, attributes: Optional[dict] = None):
122123
"""Sync context manager for adding telemetry span to a code block.
123-
124+
124125
Args:
125126
operation_name: Name of the operation for the span
126127
attributes: Optional dictionary of attributes to add to the span
127-
128+
128129
Example:
129130
with trace_sync_context("blob_upload", {"file_name": file_name}):
130131
blob_client.upload_blob(data)
@@ -134,7 +135,7 @@ def trace_sync_context(operation_name: str, attributes: Optional[dict] = None):
134135
if attributes:
135136
for key, value in attributes.items():
136137
span.set_attribute(key, str(value))
137-
138+
138139
try:
139140
yield span
140141
span.set_status(Status(StatusCode.OK))
@@ -146,17 +147,14 @@ def trace_sync_context(operation_name: str, attributes: Optional[dict] = None):
146147

147148
def add_span_attributes(attributes: dict):
148149
"""Add attributes to the current span.
149-
150+
150151
Args:
151152
attributes: Dictionary of attributes to add
152-
153+
153154
Example:
154155
add_span_attributes({"user_id": user_id, "batch_id": batch_id})
155156
"""
156157
span = trace.get_current_span()
157158
if span and span.is_recording():
158159
for key, value in attributes.items():
159160
span.set_attribute(key, str(value))
160-
161-
162-
import asyncio

src/backend/sql_agents/process_batch.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
)
1818
from common.services.batch_service import BatchService
1919
from common.storage.blob_factory import BlobStorageFactory
20-
from common.telemetry import trace_context, add_span_attributes
20+
from common.telemetry import trace_context
2121

2222
from fastapi import HTTPException
2323

@@ -40,8 +40,8 @@ async def process_batch_async(
4040
"""Central batch processing function to process each file in the batch"""
4141
# Add telemetry span for the entire batch processing operation
4242
async with trace_context("process_batch", {
43-
"batch_id": batch_id,
44-
"convert_from": convert_from,
43+
"batch_id": batch_id,
44+
"convert_from": convert_from,
4545
"convert_to": convert_to
4646
}):
4747
logger.info("Processing batch: %s", batch_id)

0 commit comments

Comments
 (0)