-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyRoleEnvironmentTelemetryInitializer.cs
75 lines (66 loc) · 3.03 KB
/
MyRoleEnvironmentTelemetryInitializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Concurrent;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
namespace Company.Function
{
// This class was taken largely from https://raw.githubusercontent.com/Microsoft/ApplicationInsights-dotnet-server/91016d62f3181e10d4cf589ef8fd64dadb6b54a2/Src/WindowsServer/WindowsServer.Shared/AzureWebAppRoleEnvironmentTelemetryInitializer.cs,
// but refactored so that it did not use WEBSITE_HOSTNAME, which is determined to be unreliable for functions during slot swaps.
/// <summary>
/// A telemetry initializer that will gather Azure Web App Role Environment context information.
/// </summary>
internal class MyRoleEnvironmentTelemetryInitializer : ITelemetryInitializer
{
internal const string AzureWebsiteName = "WEBSITE_SITE_NAME";
internal const string AzureWebsiteSlotName = "WEBSITE_SLOT_NAME";
private const string DefaultProductionSlotName = "production";
private const string WebAppSuffix = ".azurewebsites.net";
private ConcurrentDictionary<string, string> _siteNodeNames = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Initializes <see cref="ITelemetry" /> device context.
/// </summary>
/// <param name="telemetry">The telemetry to initialize.</param>
public void Initialize(ITelemetry telemetry)
{
if (telemetry == null)
{
return;
}
Lazy<string> siteSlotName = new Lazy<string>(() =>
{
// We cannot cache these values as the environment variables can change on the fly.
return GetAzureWebsiteUniqueSlotName();
});
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
{
telemetry.Context.Cloud.RoleName = siteSlotName.Value;
}
var internalContext = telemetry.Context.GetInternalContext();
if (string.IsNullOrEmpty(internalContext.NodeName) &&
!string.IsNullOrEmpty(siteSlotName.Value))
{
internalContext.NodeName = _siteNodeNames.GetOrAdd(siteSlotName.Value, p =>
{
// maintain previous behavior of node having the full url
return p += WebAppSuffix;
});
}
RequestTelemetry request = telemetry as RequestTelemetry;
if (request != null)
{
var builder = new UriBuilder(request.Url);
builder.Host = "hello-world";
request.Url = builder.Uri;
}
}
/// <summary>
/// Gets a value that uniquely identifies the site and slot.
/// </summary>
private static string GetAzureWebsiteUniqueSlotName()
{
return "hello-world";
}
}
}