Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oleh-zheleznyak/5f5eb59c7ccf9501119df67767f15708 to your computer and use it in GitHub Desktop.
Save oleh-zheleznyak/5f5eb59c7ccf9501119df67767f15708 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using Microsoft.ApplicationInsights.Channel;
using Serilog.Events;
using Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters;
namespace YourCompany.YourService.YourProject.Serilog
{
public class OperationTelemetryConverter : TraceTelemetryConverter
{
const string OperationId = "Operation Id";
const string ParentId = "Parent Id";
public override IEnumerable<ITelemetry> Convert(LogEvent logEvent, IFormatProvider formatProvider)
{
foreach (var telemetry in base.Convert(logEvent, formatProvider))
{
if (TryGetScalarProperty(logEvent , OperationId, out var operationId))
telemetry.Context.Operation.Id = operationId.ToString();
if (TryGetScalarProperty(logEvent, ParentId, out var parentId))
telemetry.Context.Operation.ParentId = parentId.ToString();
yield return telemetry;
}
}
private bool TryGetScalarProperty(LogEvent logEvent, string propertyName, out object value)
{
var hasScalarValue =
logEvent.Properties.TryGetValue(propertyName, out var someValue) &&
(someValue is ScalarValue);
value = hasScalarValue ? ((ScalarValue)someValue).Value : default;
return hasScalarValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment