Serilog.Sinks.ApplicationInsights 4.1.0

Serilog.Sinks.ApplicationInsights NuGet Version

A sink for Serilog that writes events to Microsoft Application Insights. This sink comes with several defaults that send Serilog LogEvent messages to Application Insights as either EventTelemetry or TraceTelemetry.

Configuring

The simplest way to configure Serilog to send data to a Application Insights dashboard via instrumentation key is to use current active telemetry configuration which is already initialised in most application types like ASP.NET Core, Azure Functions etc.:

var log = new LoggerConfiguration()
    .WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Traces)
    .CreateLogger();

.. or as EventTelemetry:

var log = new LoggerConfiguration()
    .WriteTo.ApplicationInsights(TelemetryConfiguration.Active, TelemetryConverter.Events)
    .CreateLogger();

You can also pass an instrumentation key and this sink will create a new TelemetryConfiguration based on it, however it's actively discouraged compared to using already initialised telemetry configuration, as your telemetry won't be properly correlated.

Note: Whether you choose Events or Traces, if the LogEvent contains any exceptions it will always be sent as ExceptionTelemetry.

TelemetryConfiguration.Active is deprecated in the App Insights SDK for .NET Core, what do I do?

The singleton TelemetryConfiguration.Active has been deprecated in the Application Insights SDK on .NET Core in favor of dependency injection pattern .

Therefore, now we need to pass in the TelemetryConfiguration instance that was added either by services.AddApplicationInsightsTelemetryWorkerService() (if you're developing a non-http application) or services.AddApplicationInsightsTelemetry() (if you're developing an ASP.Net Core application) during Startup in ConfigureServices.

Log.Logger = new LoggerConfiguration()
    .WriteTo.ApplicationInsights(
        serviceProvider.GetRequiredService<TelemetryConfiguration>(),
	TelemetryConverter.Traces)
    .CreateLogger();

However, you probably want to setup your Logger as close to the entry point of your application as possible, so that any startup errors can be caught and properly logged. The problem is that now we're in a chicken-and-egg situation: we want to setup the logger early, but we need the TelemetryConfiguration which still haven't been added to our DI container.

Luckily from version 4.0.x of the Serilog.Extensions.Hosting we have the possibility to configure a bootstrap logger to capture early errors, and then change it using DI dependant services once they are configured.

// dotnet add package serilog.extensions.hosting -v 4.0.0-*

public static class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .CreateBootstrapLogger();

        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "An unhandled exception occurred during bootstrapping");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
                .WriteTo.ApplicationInsights(
		    services.GetRequiredService<TelemetryConfiguration>(),
		    TelemetryConverter.Traces))
            .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

Configuring with ReadFrom.Configuration()

Configuring in code, as shown above, is recommended because the existing TelemetryClient can be injected.

The following configuration shows how to create an ApplicationInsights sink with ReadFrom.Configuration(configuration).

{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "[your connection string here]",
          "telemetryConverter":
	    "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "Sample"
    }
  }
}

The telemetryConverter has to be specified with the full type name and the assembly name.

A connectionString can be omitted if it's supplied in the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.

What does the sink submit?

By default, trace telemetry submits:

  • rendered message in trace's standard message property.
  • severity in trace's standard severityLevel property.
  • timestamp in trace's standard timestamp property.
  • messageTemplate in customDimensions.
  • custom log properties as customDimensions.

Event telemetry submits:

  • message template as event name.
  • renderedMessage in customDimensions.
  • timestamp in event's standard timestamp property.
  • custom log properties as customDimensions.

Exception telemetry submits:

  • exception as standard AI exception.
  • severity in trace's standard severityLevel property.
  • timestamp in trace's standard timestamp property.
  • custom log properties as customDimensions.

Note that log context properties are also included in customDimensions when Serilog is configured with .Enrich.FromLogContext().

How custom properties are logged?

By default custom properties are converted to compact JSON, for instance:

var position = new { Latitude = 25, Longitude = 134 };
var elapsedMs = 34;
var numbers = new int[] { 1, 2, 3, 4 };

Logger.Information("Processed {@Position} in {Elapsed:000} ms., str {str}, numbers: {numbers}",
    position, elapsedMs, "test", numbers);

will produce the following properties in customDimensions:

Property Value
Elapsed 34
Position {"Latitude":25,"Longitude":134}
numbers [1,2,3,4]

This is a breaking change from v2 which was producing these properties:

Property Value
Elapsed 34
Position.Latitude 25
Position.Longitude 134
numbers.0 1
numbers.1 2
numbers.2 3
numbers.3 4

You can revert the old behavior by overriding standard telemetry formatter, for instance:

private class DottedOutTraceTelemetryConverter : TraceTelemetryConverter
{
    public override IValueFormatter ValueFormatter => new ApplicationInsightsDottedValueFormatter();
}

Customizing

Additionally, you can also customize whether to send the LogEvents at all, if so which type(s) of Telemetry to send and also what to send (all or no LogEvent properties at all) by passing your own ITelemetryConverter instead of TelemetryConverter.Traces or TelemetryConverter.Events by either implementing your own ITelemetryConverter or deriving from TraceTelemetryConverter or EventTelemetryConverter and overriding specific bits.

Log.Logger = new LoggerConfiguration()
    .WriteTo.ApplicationInsights(configuration, new CustomConverter())
    .CreateLogger();
// ...

private class CustomConverter : TraceTelemetryConverter
{
    public override IEnumerable<ITelemetry> Convert(LogEvent logEvent, IFormatProvider formatProvider)
    {
        // first create a default TraceTelemetry using the sink's default logic
        // .. but without the log level, and (rendered) message (template) included in the Properties
        foreach (ITelemetry telemetry in base.Convert(logEvent, formatProvider))
        {
            // then go ahead and post-process the telemetry's context to contain the user id as desired
            if (logEvent.Properties.ContainsKey("UserId"))
            {
                telemetry.Context.User.Id = logEvent.Properties["UserId"].ToString();
            }
            // post-process the telemetry's context to contain the operation id
            if (logEvent.Properties.ContainsKey("operation_Id"))
            {
                telemetry.Context.Operation.Id = logEvent.Properties["operation_Id"].ToString();
            }
            // post-process the telemetry's context to contain the operation parent id
            if (logEvent.Properties.ContainsKey("operation_parentId"))
            {
                telemetry.Context.Operation.ParentId = logEvent.Properties["operation_parentId"].ToString();
            }
            // typecast to ISupportProperties so you can manipulate the properties as desired
            ISupportProperties propTelematry = (ISupportProperties)telemetry;

            // find redundant properties
            var removeProps = new[] { "UserId", "operation_parentId", "operation_Id" };
            removeProps = removeProps.Where(prop => propTelematry.Properties.ContainsKey(prop)).ToArray();

            foreach (var prop in removeProps)
            {
                // remove redundant properties
                propTelematry.Properties.Remove(prop);
            }

            yield return telemetry;
        }
    }
}

If you want to skip sending a particular LogEvent, just return null from your own converter method.

Customising included properties

The easiest way to customise included properties is to subclass one of the ITelemetryConverter implementations. For instance, let's include renderedMessage in event telemetry:

private class IncludeRenderedMessageConverter : EventTelemetryConverter
{
    public override void ForwardPropertiesToTelemetryProperties(LogEvent logEvent, 
        ISupportProperties telemetryProperties, IFormatProvider formatProvider)
    {
        base.ForwardPropertiesToTelemetryProperties(logEvent, telemetryProperties, formatProvider,
            includeLogLevel: false,
            includeRenderedMessage: true,
            includeMessageTemplate: false);
    }
}

How, When and Why to Flush Messages Manually

Or: Where did my Messages go?

As explained by the Application Insights documentation , the default behaviour of the AI client is to buffer messages and send them to AI in batches whenever the client seems fit. However, this may lead to lost messages when your application terminates while there are still unsent messages in said buffer.

You can control when AI shall flush its messages, for example when your application closes:

  1. Create a custom TelemetryClient and hold on to it in a field or property:
// private TelemetryClient _telemetryClient;

// ...
_telemetryClient = new TelemetryClient()
            {
                InstrumentationKey = "<My AI Instrumentation Key>"
            };
  1. Use that custom TelemetryClient to initialize the Sink:
var log = new LoggerConfiguration()
    .WriteTo
	.ApplicationInsights(_telemetryClient, TelemetryConverter.Events)
    .CreateLogger();
  1. Call .Flush() on the TelemetryClient whenever you deem necessary, i.e. Application Shutdown:
_telemetryClient.Flush();

// The AI documentation mentions that calling `Flush()` *can* be asynchronous and non-blocking so
// depending on the underlying Channel to AI you might want to wait some time
// specific to your application and its connectivity constraints for the flush to finish.

await Task.Delay(1000);

// or 

System.Threading.Thread.Sleep(1000);

Including Operation Id

Application Insight's operation id is pushed out if you set operationId LogEvent property. If it's present, AI's operation id will be overridden by the value from this property.

This can be set like so:


public class OperationIdEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (logEvent.Properties.TryGetValue("RequestId", out var requestId))
        {
            logEvent.AddPropertyIfAbsent(new LogEventProperty("operationId", requestId));
        }
    }
}

Including Version

Application Insight supports component version and is pushed out if you set version log event property. If it's present, AI's operation version will include the value from this property.

Using with Azure Functions

Azure functions has out of the box integration with Application Insights, which automatically logs functions execution start, end, and any exception. Please refer to the original documenation on how to enable it.

This sink can enrich AI messages, preserving operation_Id and other context information which is already provided by functions runtime. The easiest way to configure Serilog in this case is to use the injected TelemetryClient which should be automatically configured by the environment through the APPLICATIONINSIGHTS_CONNECTION_STRING appsetting. You can, for instance, initialise logging in the static constructor:

[assembly: FunctionsStartup(typeof(MyFunctions.Startup))]
namespace MyFunctions
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<ILoggerProvider>((sp) => 
            {
                Log.Logger = new LoggerConfiguration()
                    .Enrich.FromLogContext()
                    .WriteTo.ApplicationInsights(sp.GetRequiredService<TelemetryClient>(), TelemetryConverter.Traces)
                    .CreateLogger();
                return new SerilogLoggerProvider(Log.Logger, true);
            });
        }
    }
}

Copyright © 2022 Serilog Contributors - Provided under the Apache License, Version 2.0.

See also: Serilog Documentation

Showing the top 20 packages that depend on Serilog.Sinks.ApplicationInsights.

Packages Downloads
Finsa.CaravanCore
Package Description
62
Finsa.CaravanCore
Package Description
65
Finsa.CaravanCore
Package Description
74
Finsa.CaravanCore
Package Description
75
Finsa.CaravanCore
Package Description
82
Finsa.CaravanCore
Package Description
96
Finsa.CaravanCore
Package Description
107
Finsa.CaravanCore
Package Description
110
Finsa.CaravanCore
Package Description
114
Finsa.CaravanCore
Package Description
116
Finsa.CaravanCore
Package Description
162
Finsa.CaravanCore
Package Description
187
Finsa.CaravanCore
Package Description
299
Finsa.CaravanCore
Package Description
393
Finsa.CaravanCore
Package Description
443
Finsa.CaravanCore
Package Description
482
Finsa.CaravanCore
Package Description
582
Finsa.CaravanCore
Package Description
1,269
Finsa.CaravanCore
Package Description
2,173

.NET Framework 4.6.2

.NET 6.0

.NET Standard 2.0

Version Downloads Last updated
4.1.0 1 12/05/2025
4.1.0-dev-02311 1 12/07/2025
4.1.0-dev-02307 1 11/19/2025
4.1.0-dev-02304 25 03/30/2025
4.0.1-dev-02303 27 03/31/2025
4.0.1-dev-00050 21 03/31/2025
4.0.1-dev-00049 19 03/31/2025
4.0.1-dev-00046 18 11/09/2024
4.0.1-dev-00043 29 02/05/2024
4.0.1-dev-00040 23 02/05/2024
4.0.1-dev-00038 25 02/05/2024
4.0.0 75 08/16/2022
4.0.0-dev-00034 28 02/05/2024
4.0.0-dev-00030 30 02/05/2024
4.0.0-dev-00028 27 02/05/2024
4.0.0-dev-00022 27 02/05/2024
4.0.0-dev-00018 28 02/05/2024
4.0.0-dev-00016 30 02/05/2024
4.0.0-dev-00013 26 02/05/2024
4.0.0-dev-00003 25 02/05/2024
4.0.0-dev-00002 27 02/05/2024
4.0.0-dev-00001 26 02/05/2024
3.1.1-dev-00170 23 02/05/2024
3.1.1-dev-00169 29 02/05/2024
3.1.1-dev-00167 23 02/05/2024
3.1.1-dev-00165 30 02/05/2024
3.1.0 1,112 06/21/2020
3.0.4 42 02/11/2020
3.0.3 22 02/12/2024
3.0.2 26 02/12/2024
3.0.1 26 02/12/2024
3.0.0 26 02/12/2024
2.6.4 25 02/12/2024
2.6.3 30 02/12/2024
2.6.2 25 02/12/2024
2.6.1 27 02/12/2024
2.6.0 27 02/12/2024
2.5.2 24 02/12/2024
2.5.1 30 02/12/2024
2.5.0 23 02/12/2024
2.5.0-dev-00094 32 02/05/2024
2.5.0-dev-00093 26 02/05/2024
2.2.2 25 02/12/2024
2.2.1 25 02/12/2024
2.2.1-dev-00083 28 02/05/2024
2.2.1-dev-00080 23 02/05/2024
2.2.1-dev-00073 31 02/05/2024
2.2.0 24 02/12/2024
2.1.0 30 02/12/2024
2.0.56 26 02/05/2024
2.0.55 26 02/05/2024
2.0.52 24 02/05/2024
2.0.45 23 02/05/2024
2.0.43 27 02/05/2024
2.0.41 29 02/05/2024
2.0.37 28 02/05/2024
2.0.35 26 02/05/2024
2.0.33 28 02/05/2024
2.0.32 27 02/05/2024
2.0.31 26 02/05/2024
2.0.28 29 02/05/2024
2.0.27 29 02/05/2024
2.0.24 27 02/05/2024
2.0.23 26 02/05/2024
2.0.21 28 02/05/2024
2.0.20 29 02/05/2024
2.0.19 26 02/05/2024
2.0.18-pre 27 02/05/2024
2.0.16-pre 28 02/05/2024
2.0.13-pre 28 02/05/2024
2.0.12 25 02/05/2024
2.0.11-pre 27 02/05/2024
2.0.10-pre 25 02/05/2024
2.0.9-pre 28 02/05/2024
2.0.8-pre 26 02/05/2024
2.0.7-pre 23 02/05/2024
2.0.6-pre 26 02/05/2024
2.0.5-pre 33 02/05/2024
2.0.4-pre 30 02/05/2024
2.0.3-pre 24 02/05/2024
2.0.2-pre 32 02/05/2024
2.0.1-pre 26 02/05/2024
1.4.139 28 02/05/2024
1.4.128 26 02/05/2024
1.4.118 25 02/05/2024
1.4.113 25 02/05/2024
1.4.102 25 02/05/2024
1.4.99 23 02/05/2024
1.4.97 24 02/05/2024
1.4.76 25 02/05/2024
1.4.75 27 02/05/2024
1.4.39 26 02/05/2024
1.4.34 30 02/05/2024
1.4.28 27 02/05/2024
1.4.27 26 02/05/2024
1.4.23 32 02/05/2024
1.4.22 29 02/05/2024
1.4.21 26 02/05/2024
1.4.18 27 02/05/2024
1.4.15 0 11/04/2014
1.4.14 0 10/23/2014
1.4.13 0 10/23/2014
1.4.12 0 10/12/2014
1.4.11 0 10/08/2014
1.4.10 0 09/26/2014
1.4.9 0 09/17/2014
1.4.8 0 09/11/2014
1.4.7 0 09/01/2014
1.4.6 0 08/31/2014
1.4.5 0 08/27/2014
1.4.4 0 08/27/2014
1.4.3 0 08/25/2014
1.4.2 0 08/23/2014
1.4.1 0 08/23/2014
1.3.43 0 08/04/2014
1.3.42 0 07/30/2014
1.3.41 0 07/28/2014
1.3.40 0 07/26/2014
1.3.39 0 07/25/2014
1.3.37 0 07/25/2014
1.3.36 0 07/20/2014
1.3.35 0 07/17/2014
1.3.34 0 07/06/2014
1.3.33 0 06/30/2014
1.3.30 0 06/19/2014
1.3.29 0 06/19/2014
1.3.28 0 06/19/2014
1.3.27 0 06/18/2014
1.3.26 0 06/18/2014