|
| 1 | +using Microsoft.ApplicationInsights.Channel; |
| 2 | +using Microsoft.ApplicationInsights.DataContracts; |
| 3 | +using Microsoft.ApplicationInsights.Extensibility; |
| 4 | +using Serilog; |
| 5 | +using Serilog.Configuration; |
| 6 | +using Serilog.Events; |
| 7 | +using Serilog.ExtensionMethods; |
| 8 | +using System; |
| 9 | +using System.Linq; |
| 10 | + |
| 11 | +namespace ApplicationInsightsLib |
| 12 | +{ |
| 13 | + public static class ApplicationInsightsExtensions |
| 14 | + { |
| 15 | + public static LoggerConfiguration MyApplicationInsights( this LoggerSinkConfiguration sinkConfiguration ) |
| 16 | + { |
| 17 | + return sinkConfiguration.ApplicationInsightsTraces("4f9d01cc-aa54-4270-ad8f-04b89088b8a2", logEventToTelemetryConverter: LogEventToTelemetryConverter); |
| 18 | + } |
| 19 | + private static ITelemetry LogEventToTelemetryConverter(LogEvent logEvent, IFormatProvider formatProvider) |
| 20 | + { |
| 21 | + // Original code: https://github.com/serilog/serilog-sinks-applicationinsights |
| 22 | + |
| 23 | + // first create a default TraceTelemetry using the sink's default logic |
| 24 | + // .. but without the log level, and (rendered) message (template) included in the Properties |
| 25 | + ITelemetry telemetry; |
| 26 | + |
| 27 | + if (logEvent.Exception != null) |
| 28 | + { |
| 29 | + telemetry = logEvent.ToDefaultExceptionTelemetry( |
| 30 | + formatProvider, |
| 31 | + includeLogLevelAsProperty: false, |
| 32 | + includeRenderedMessageAsProperty: false, |
| 33 | + includeMessageTemplateAsProperty: false); |
| 34 | + } |
| 35 | + else |
| 36 | + { |
| 37 | + telemetry = logEvent.ToDefaultTraceTelemetry( |
| 38 | + formatProvider, |
| 39 | + includeLogLevelAsProperty: false, |
| 40 | + includeRenderedMessageAsProperty: false, |
| 41 | + includeMessageTemplateAsProperty: false); |
| 42 | + } |
| 43 | + |
| 44 | + ISupportProperties telemetryProperties = (ISupportProperties)telemetry; |
| 45 | + |
| 46 | + |
| 47 | + if (logEvent.Properties.ContainsKey("operation_Id")) |
| 48 | + { |
| 49 | + telemetry.Context.Operation.Id = logEvent.Properties["operation_Id"].ToString(); |
| 50 | + telemetryProperties.Properties.Remove("parentId"); |
| 51 | + } |
| 52 | + |
| 53 | + if (logEvent.Properties.ContainsKey("operation_parentId")) |
| 54 | + { |
| 55 | + telemetry.Context.Operation.ParentId = logEvent.Properties["operation_parentId"].ToString(); |
| 56 | + telemetryProperties.Properties.Remove("operation_parentId"); |
| 57 | + } |
| 58 | + |
| 59 | + return telemetry; |
| 60 | + } |
| 61 | + |
| 62 | + } |
| 63 | +} |
0 commit comments