Skip to content

Commit 4918d37

Browse files
author
Olesia Solonko
committed
Refactor Application Insight integration
1 parent 95af856 commit 4918d37

4 files changed

Lines changed: 115 additions & 1 deletion

File tree

docker-compose.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ services:
4141
- CONTAINER_HOST=0.0.0.0
4242
- CONTAINER_PORT=5000
4343
- PYGEOAPI_SERVER_URL=http://localhost:5000
44-
#- APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=b4d987bc-1712-4026-aafb-f590fd854ab3;IngestionEndpoint=https://norwayeast-0.in.applicationinsights.azure.com/;LiveEndpoint=https://norwayeast.livediagnostics.monitor.azure.com/;ApplicationId=9fc4692c-7609-4abb-b547-49203ac14d4a
4544
profiles:
4645
- local
4746

@@ -52,6 +51,7 @@ services:
5251
- "8080:80"
5352
environment:
5453
- API_BASE_URL=http://backend-local:5000
54+
- APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=b4d987bc-1712-4026-aafb-f590fd854ab3;IngestionEndpoint=https://norwayeast-0.in.applicationinsights.azure.com/;LiveEndpoint=https://norwayeast.livediagnostics.monitor.azure.com/;ApplicationId=9fc4692c-7609-4abb-b547-49203ac14d4a
5555
depends_on:
5656
- backend-local
5757
profiles:

frontend/build.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ if (apiBaseUrl) {
1818
html = html.replace("</head>", `${scriptTag}\n</head>`);
1919
}
2020

21+
// Add Application Insights connection string if available
22+
const appInsightsConnectionString = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING || "";
23+
if (appInsightsConnectionString) {
24+
const appInsightsScript = `<script>window.APPLICATIONINSIGHTS_CONNECTION_STRING = "${appInsightsConnectionString}";</script>`;
25+
html = html.replace("</head>", `${appInsightsScript}\n</head>`);
26+
}
27+
2128
const distHtmlPath = path.join(__dirname, "dist", "index.html");
2229
fs.writeFileSync(distHtmlPath, html);
2330

@@ -27,3 +34,9 @@ const distJsDir = path.join(__dirname, "dist", "js");
2734
fs.readdirSync(srcJsDir).forEach((file) => {
2835
fs.copyFileSync(path.join(srcJsDir, file), path.join(distJsDir, file));
2936
});
37+
38+
if (appInsightsConnectionString) {
39+
console.log("Application Insights: Enabled");
40+
} else {
41+
console.log("Application Insights: Disabled (no connection string provided)");
42+
}

frontend/src/index.html

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
<!-- <script src="js/points-layer.js"></script> -->
1818
<!-- Add this to your index.html file, wherever your other script tags are located -->
1919
<!-- <script src="js/norway-hazard-tiles.js"></script> -->
20+
<!-- Application Insights -->
21+
<script src="js/appInsights.js"></script>
2022
<style>
2123
/* Reset and full screen layout */
2224
* {

frontend/src/js/appInsights.js

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
(function() {
2+
const connectionString = window.APPLICATIONINSIGHTS_CONNECTION_STRING;
3+
4+
if (!connectionString) {
5+
return;
6+
}
7+
8+
const script = document.createElement('script');
9+
script.src = 'https://js.monitor.azure.com/scripts/b/ai.2.min.js';
10+
script.async = true;
11+
12+
script.onload = function() {
13+
const appInsights = new Microsoft.ApplicationInsights.ApplicationInsights({
14+
config: {
15+
connectionString: connectionString,
16+
enableAutoRouteTracking: false,
17+
disableExceptionTracking: true,
18+
disableTelemetry: false,
19+
samplingPercentage: 100
20+
}
21+
});
22+
23+
appInsights.loadAppInsights();
24+
25+
// Generate anonymous user ID for session tracking
26+
const userId = sessionStorage.getItem('ai_user') ||
27+
'user_' + Math.random().toString(36).substring(2, 15);
28+
sessionStorage.setItem('ai_user', userId);
29+
appInsights.setAuthenticatedUserContext(userId);
30+
31+
// Collect comprehensive user statistics
32+
const userStats = {
33+
referrer: document.referrer || 'direct',
34+
userAgent: navigator.userAgent,
35+
language: navigator.language,
36+
languages: navigator.languages ? navigator.languages.join(',') : '',
37+
screenResolution: `${screen.width}x${screen.height}`,
38+
colorDepth: screen.colorDepth,
39+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
40+
platform: navigator.platform,
41+
cookieEnabled: navigator.cookieEnabled,
42+
onLine: navigator.onLine,
43+
deviceMemory: navigator.deviceMemory || 'unknown',
44+
connection: navigator.connection ? {
45+
effectiveType: navigator.connection.effectiveType,
46+
downlink: navigator.connection.downlink,
47+
rtt: navigator.connection.rtt
48+
} : 'unknown'
49+
};
50+
51+
// Track page view with enhanced user statistics
52+
appInsights.trackPageView({
53+
name: 'Tsunami Map',
54+
properties: userStats
55+
});
56+
57+
// Track user location (with permission)
58+
if (navigator.geolocation && 'geolocation' in navigator) {
59+
navigator.geolocation.getCurrentPosition(
60+
function(position) {
61+
// Track approximate location (country/region level for privacy)
62+
appInsights.trackEvent('UserLocation', {
63+
latitude: Math.round(position.coords.latitude * 10) / 10, // Rounded for privacy
64+
longitude: Math.round(position.coords.longitude * 10) / 10, // Rounded for privacy
65+
accuracy: position.coords.accuracy > 1000 ? 'low' : 'high'
66+
});
67+
},
68+
function(error) {
69+
// Track location access denied/failed
70+
appInsights.trackEvent('LocationAccessDenied', {
71+
error: error.message || 'unknown'
72+
});
73+
},
74+
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 300000 }
75+
);
76+
}
77+
78+
// Track map interactions
79+
window.trackMapInteraction = function(action, properties) {
80+
appInsights.trackEvent('MapInteraction', {
81+
action: action,
82+
...properties,
83+
timestamp: new Date().toISOString()
84+
});
85+
};
86+
87+
// Track session duration
88+
let sessionStart = Date.now();
89+
window.addEventListener('beforeunload', function() {
90+
const sessionDuration = Math.round((Date.now() - sessionStart) / 1000);
91+
appInsights.trackEvent('SessionEnd', {
92+
durationSeconds: sessionDuration,
93+
userId: userId
94+
});
95+
});
96+
};
97+
98+
document.head.appendChild(script);
99+
})();

0 commit comments

Comments
 (0)