Created
August 4, 2019 14:10
-
-
Save oleh-zheleznyak/5f5eb59c7ccf9501119df67767f15708 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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