Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 286

Sitecore use Application Insights Metrics and Telemetry

$
0
0

Although Sitecore have an integration for Application Insights (which is part of Azure Monitor), you can implement the TelemetryClient yourself. This is useful if you wish to log Metrics or Trace your own code, without involving the complete Sitecore solution. There is no need for configuration changes if all you want is to get some metrics for your own subsystem within Sitecore.

Application Insights is very easy to work with. First you need to install the Microsoft.ApplicationInsights NuGet Package.

In order to use Application Insights you must create a TelemetryClient:

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;

namespace MyCode
{
  public static class TelemetryFactory
  {
    /// <summary>
    /// Create a new TelemetryClient
    /// </summary>
    /// <param name="instrumentationKey">The Application Insights key</param>
    /// <param name="roleInstance">The name of your instance</param>
    /// <param name="roleName">The name of your role</param>
    /// <returns></returns>
    public static TelemetryClient GetTelemetryClient(string instrumentationKey, string roleInstance, string roleName)
    {
      var telemetryConfiguration = new TelemetryConfiguration {InstrumentationKey = instrumentationKey};
      telemetryConfiguration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
      telemetryConfiguration.TelemetryInitializers.Add(new CloudRoleInitializer(roleInstance, roleName));
      return new TelemetryClient(telemetryConfiguration);
    }
  }
}

With the TelemetryClient in hand, it’s easy to track metrics:

TelemetryClient _telemetryClient = 
  TelemetryFactory.GetTelemetryClient("my-key", "Application Name", "Application Name");

_telemetryClient.GetMetric(
  new MetricIdentifier("MySystem", $"Deleted Users")
).TrackValue(1);

The tracked telemetry will appear in Application Insights shortly after:

Application Insights Metrics

Application Insights Metrics

If you wish to log traces, it is equally easy:

var trace = new TraceTelemetry
{
  SeverityLevel = SeverityLevel.Information,
  Message = $"xxx Deleted User xxx"
};

_telemetryClient.TrackTrace(trace);

The traces appear as log lines in Application Insights:

Application Insights Trace

Application Insights Trace

MORE TO READ:


Viewing all articles
Browse latest Browse all 286