Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ namespace Microsoft.ApplicationInsights.DiagnosticSourceListener
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.ApplicationInsights.DataContracts;

internal class DiagnosticSourceListenerSubscription : IObserver<KeyValuePair<string, object>>
{
private readonly string listenerName;
private readonly TelemetryClient telemetryClient;
private readonly OnEventWrittenHandler onEventWrittenHandler;

public DiagnosticSourceListenerSubscription(string listenerName, TelemetryClient telemetryClient)
public DiagnosticSourceListenerSubscription(string listenerName, TelemetryClient telemetryClient, OnEventWrittenHandler onEventWrittenHandler)
{
if (listenerName == null)
{
Expand All @@ -28,8 +27,14 @@ public DiagnosticSourceListenerSubscription(string listenerName, TelemetryClient
throw new ArgumentNullException(nameof(telemetryClient));
}

if (onEventWrittenHandler == null)
{
throw new ArgumentNullException(nameof(onEventWrittenHandler));
}

this.listenerName = listenerName;
this.telemetryClient = telemetryClient;
this.onEventWrittenHandler = onEventWrittenHandler;
}

public void OnCompleted()
Expand All @@ -46,25 +51,14 @@ public void OnError(Exception error)
/// <param name="event">The event (message and payload) from the diagnostic source.</param>
public void OnNext(KeyValuePair<string, object> @event)
{
var message = @event.Key;
var payload = @event.Value;

var telemetry = new TraceTelemetry(message, SeverityLevel.Information);
telemetry.Properties.Add("DiagnosticSource", this.listenerName);

// Transfer properties from payload to telemetry
if (payload != null)
try
{
foreach (var property in DeclaredPropertiesCache.GetDeclaredProperties(payload))
{
if (!property.IsSpecialName)
{
telemetry.Properties.Add(property.Name, Convert.ToString(property.GetValue(payload), CultureInfo.InvariantCulture));
}
}
this.onEventWrittenHandler(this.listenerName, @event.Key, @event.Value, this.telemetryClient);
}
catch (Exception ex)
{
this.telemetryClient.TrackException(ex);
}

this.telemetryClient.TrackTrace(telemetry);
}
}
}
56 changes: 55 additions & 1 deletion src/DiagnosticSourceListener/DiagnosticSourceTelemetryModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,54 @@ namespace Microsoft.ApplicationInsights.DiagnosticSourceListener
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Implementation;

/// <summary>
/// Delegate to apply custom formatting to Application Insights trace telemetry from the Diagnostics Source data.
/// </summary>
/// <param name="sourceName">Name of the DiagnosticsSource (as implemented by a DiagnosticsListener).</param>
/// <param name="message">Name of the event.</param>
/// <param name="payload">Data associated with the event.</param>
/// <param name="client">Telemetry client to report telemetry to.</param>
public delegate void OnEventWrittenHandler(string sourceName, string message, object payload, TelemetryClient client);

/// <summary>
/// A module to forward diagnostic source events to Application Insights.
/// </summary>
public sealed class DiagnosticSourceTelemetryModule : IObserver<DiagnosticListener>, ITelemetryModule, IDisposable
{
private readonly OnEventWrittenHandler onEventWrittenHandler;

private TelemetryClient client;
private IDisposable allDiagnosticListenersSubscription;
private List<IDisposable> diagnosticListenerSubscriptions;

/// <summary>
/// Initializes a new instance of the <see cref="DiagnosticSourceTelemetryModule"/> class.
/// </summary>
public DiagnosticSourceTelemetryModule() : this(Track)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="DiagnosticSourceTelemetryModule"/> class.
/// </summary>
/// <param name="onEventWrittenHandler">Action to be executed each time an event is written to format and send via the configured <see cref="TelemetryClient"/></param>
public DiagnosticSourceTelemetryModule(OnEventWrittenHandler onEventWrittenHandler)
{
if (onEventWrittenHandler == null)
{
throw new ArgumentNullException(nameof(onEventWrittenHandler));
}

this.onEventWrittenHandler = onEventWrittenHandler;
}

/// <summary>
/// Gets the list of DiagnosticSource listening requests (information about which DiagnosticSources should be traced).
/// </summary>
Expand Down Expand Up @@ -90,11 +124,31 @@ void IObserver<DiagnosticListener>.OnNext(DiagnosticListener listener)
this.diagnosticListenerSubscriptions = new List<IDisposable>();
}

var subscription = new DiagnosticSourceListenerSubscription(listener.Name, this.client);
var subscription = new DiagnosticSourceListenerSubscription(listener.Name, this.client, this.onEventWrittenHandler);
this.diagnosticListenerSubscriptions.Add(listener.Subscribe(subscription));
break;
}
}
}

private static void Track(string sourceName, string message, object payload, TelemetryClient client)
{
var telemetry = new TraceTelemetry(message, SeverityLevel.Information);
telemetry.Properties.Add("DiagnosticSource", sourceName);

// Transfer properties from payload to telemetry
if (payload != null)
{
foreach (var property in DeclaredPropertiesCache.GetDeclaredProperties(payload))
{
if (!property.IsSpecialName)
{
telemetry.Properties.Add(property.Name, Convert.ToString(property.GetValue(payload), CultureInfo.InvariantCulture));
}
}
}

client.TrackTrace(telemetry);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,31 @@ public void HandlesPropertiesWithNullValues()
}
}

[TestMethod]
public void CallsOnEventWrittenHandler()
{
OnEventWrittenHandler onEventWrittenHandler = (sourceName, message, payload, client) =>
{
var traceTelemetry = new TraceTelemetry("CustomPayloadProperties", SeverityLevel.Verbose);
traceTelemetry.Properties.Add("CustomPayloadProperties", "true");
client.Track(traceTelemetry);
};

using (var module = new DiagnosticSourceTelemetryModule(onEventWrittenHandler))
{
var testDiagnosticSource = new TestDiagnosticSource();
var listeningRequest = new DiagnosticSourceListeningRequest(testDiagnosticSource.Name);
module.Sources.Add(listeningRequest);

module.Initialize(GetTestTelemetryConfiguration());

testDiagnosticSource.Write("Hey!", new { Prop1 = 1234 });

TraceTelemetry telemetry = (TraceTelemetry)this.adapterHelper.Channel.SentItems.First();
Assert.IsTrue(telemetry.Properties.All(kvp => kvp.Key.Equals("CustomPayloadProperties") && kvp.Value.Equals("true")));
}
}

private TelemetryConfiguration GetTestTelemetryConfiguration(bool resetChannel = true)
{
var configuration = new TelemetryConfiguration();
Expand Down