11# appinsights_init.py - Lightweight Application Insights setup for pygeoapi
2+
23import os
34import logging
45from opencensus .ext .azure .log_exporter import AzureLogHandler
56from opencensus .ext .azure .trace_exporter import AzureExporter
67from opencensus .ext .flask .flask_middleware import FlaskMiddleware
78from opencensus .trace .samplers import ProbabilitySampler
89
10+ # Global logger for reuse
11+ _insights_logger = None
12+
913
1014def setup_app_insights (app ):
1115 """
1216 Setup lightweight Application Insights for pygeoapi
13- Only tracks user interactions and basic telemetry
17+ Tracks user interactions and basic telemetry
1418 """
1519 connection_string = os .environ .get ('APPLICATIONINSIGHTS_CONNECTION_STRING' )
1620
@@ -19,19 +23,29 @@ def setup_app_insights(app):
1923 return
2024
2125 try :
22- # Setup request tracking with low sampling rate for lightweight monitoring
26+ print ("[appinsights] Setting up Application Insights with connection string" )
27+
28+ # Initialize OpenCensus Flask middleware
2329 middleware = FlaskMiddleware (
2430 app ,
2531 exporter = AzureExporter (connection_string = connection_string ),
26- sampler = ProbabilitySampler (rate = 0.1 ) # Sample 10% of requests for lightweight monitoring
32+ sampler = ProbabilitySampler (rate = 0.1 ) # Sample 10% of requests
2733 )
2834
29- # Setup basic logging for user interactions
30- logger = logging .getLogger (__name__ )
31- logger .addHandler (AzureLogHandler (connection_string = connection_string ))
35+ # Setup base logging
36+ logging .basicConfig (level = logging .INFO )
37+ logger = logging .getLogger ('pygeoapi_insights' )
38+
39+ if not any (isinstance (h , AzureLogHandler ) for h in logger .handlers ):
40+ handler = AzureLogHandler (connection_string = connection_string )
41+ logger .addHandler (handler )
42+
3243 logger .setLevel (logging .INFO )
3344
34- # Add custom properties for better analytics
45+ global _insights_logger
46+ _insights_logger = logger # Store globally for reuse in log_user_interaction
47+
48+ # Add request attributes to spans
3549 @app .before_request
3650 def before_request ():
3751 from flask import request
@@ -41,27 +55,31 @@ def before_request():
4155 if tracer :
4256 span = tracer .current_span ()
4357 if span :
44- # Add custom properties for analytics
4558 span .add_attribute ('user_agent' , request .headers .get ('User-Agent' , '' ))
4659 span .add_attribute ('referrer' , request .headers .get ('Referer' , '' ))
4760 span .add_attribute ('api_endpoint' , request .endpoint or 'unknown' )
4861
49- print ("Application Insights configured successfully" )
62+ print ("[appinsights] Application Insights configured successfully" )
5063
5164 except Exception as e :
52- print (f"Failed to setup Application Insights: { e } " )
65+ print (f"[appinsights] Failed to setup Application Insights: { e } " )
66+ import traceback
67+ traceback .print_exc ()
5368
5469
55- # Custom logging function for user interФactions
5670def log_user_interaction (action , details = None ):
57- """Log user interactions for analytics"""
58- connection_string = os .environ .get ('APPLICATIONINSIGHTS_CONNECTION_STRING' )
59- if connection_string :
60- logger = logging .getLogger ('user_analytics' )
61- logger .addHandler (AzureLogHandler (connection_string = connection_string ))
71+ """
72+ Log user interactions for analytics
73+ """
74+ if _insights_logger is None :
75+ print ("[appinsights] Telemetry not initialized, skipping interaction log" )
76+ return
6277
63- log_data = {'action' : action }
64- if details :
65- log_data .update (details )
78+ log_data = {'action' : action }
79+ if details :
80+ log_data .update (details )
6681
67- logger .info (f"User interaction: { action } " , extra = {'custom_dimensions' : log_data })
82+ _insights_logger .info (
83+ f"User interaction: { action } " ,
84+ extra = {'custom_dimensions' : log_data }
85+ )
0 commit comments