Serilog.Sinks.ApplicationInsights 4.1.0-dev-02304

This is a prerelease version of Serilog.Sinks.ApplicationInsights.
dotnet add package Serilog.Sinks.ApplicationInsights --version 4.1.0-dev-02304
                    
NuGet\Install-Package Serilog.Sinks.ApplicationInsights -Version 4.1.0-dev-02304
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.1.0-dev-02304" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Serilog.Sinks.ApplicationInsights" Version="4.1.0-dev-02304" />
                    
Directory.Packages.props
<PackageReference Include="Serilog.Sinks.ApplicationInsights" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Serilog.Sinks.ApplicationInsights --version 4.1.0-dev-02304
                    
#r "nuget: Serilog.Sinks.ApplicationInsights, 4.1.0-dev-02304"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Serilog.Sinks.ApplicationInsights&version=4.1.0-dev-02304&prerelease
                    
Install Serilog.Sinks.ApplicationInsights as a Cake Addin
#tool nuget:?package=Serilog.Sinks.ApplicationInsights&version=4.1.0-dev-02304&prerelease
                    
Install Serilog.Sinks.ApplicationInsights as a Cake Tool

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

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (103)

Showing the top 5 NuGet packages that depend on Serilog.Sinks.ApplicationInsights:

Package Downloads
Apprio.Enablement.Telemetry.Properties

Package Description

Apprio.Enablement.Telemetry

Package Description

Serilog.Extensions.Logging.ApplicationInsights

Add application insights logging to ASP.NET Core apps with one line of code.

NanoCore

The project is inspired by years of tedious repetitions, continuously re-writing similar code-snippets and libraries, to handle common functionality, not related to the business domain, such as logging, data persistence, message queuing, documentation, validation and similar.

Arcus.Observability.Telemetry.Serilog.Sinks.ApplicationInsights

Provides capability to improve telemetry with Serilog that is sent to Azure Application Insights

GitHub repositories (14)

Showing the top 5 popular GitHub repositories that depend on Serilog.Sinks.ApplicationInsights:

Repository Stars
ardalis/CleanArchitecture
Clean Architecture Solution Template: A proven Clean Architecture Template for ASP.NET Core 9
Dotnet-Boxed/Templates
.NET project templates with batteries included, providing the minimum amount of code required to get you going faster.
microsoft/AttackSurfaceAnalyzer
Attack Surface Analyzer can help you analyze your operating system's security configuration for changes during software installation.
NuGet/NuGetGallery
NuGet Gallery is a package repository that powers https://www.nuget.org. Use this repo for reporting NuGet.org issues.
bkaankose/Wino-Mail
Built-in Mail & Calendars app clone for Windows.
Version Downloads Last updated
4.1.0-dev-02304 87 3/28/2025
4.0.1-dev-02303 79 3/28/2025
4.0.1-dev-00050 124 3/27/2025
4.0.1-dev-00049 93 3/27/2025
4.0.1-dev-00046 28,879 11/1/2024
4.0.1-dev-00043 402,667 3/15/2023
4.0.1-dev-00040 216,330 7/25/2022
4.0.1-dev-00038 2,709 6/21/2022
4.0.0 42,449,111 6/21/2022
4.0.0-dev-00034 806 6/21/2022
4.0.0-dev-00030 2,397 6/19/2022
4.0.0-dev-00028 10,533 5/12/2022
4.0.0-dev-00022 2,002 5/5/2022
4.0.0-dev-00018 1,173 5/5/2022
4.0.0-dev-00016 734 5/5/2022
4.0.0-dev-00013 780 5/4/2022
4.0.0-dev-00003 1,017 5/2/2022
4.0.0-dev-00002 747 5/1/2022
4.0.0-dev-00001 687 5/1/2022
3.1.1-dev-00170 118,009 11/12/2021
3.1.1-dev-00169 13,592 10/2/2021
3.1.1-dev-00167 1,762 10/2/2021
3.1.1-dev-00165 11,746 8/30/2021
3.1.0 40,698,946 2/12/2020
3.0.4 4,976,445 8/2/2019
3.0.3 2,076,818 4/3/2019
3.0.2 660,870 2/25/2019
3.0.1 42,530 2/20/2019
3.0.0 109,152 2/19/2019
2.6.4 522,640 2/13/2019
2.6.3 154,631 2/6/2019
2.6.2 125,072 1/28/2019
2.6.1 10,334 1/25/2019
2.6.0 3,211,473 4/6/2018
2.5.2 125,289 4/6/2018
2.5.1 509,854 2/25/2018
2.5.0 374,232 11/17/2017
2.5.0-dev-00094 1,940 2/9/2018
2.5.0-dev-00093 1,500 2/9/2018
2.2.2 8,776 11/17/2017
2.2.1 872,904 2/15/2017
2.2.1-dev-00083 1,507 11/16/2017
2.2.1-dev-00080 1,527 10/12/2017
2.2.1-dev-00073 1,514 6/19/2017
2.2.0 424,832 1/2/2017
2.1.0 83,657 7/23/2016
2.0.56 81,563 6/23/2016
2.0.55 2,265 6/20/2016
2.0.52 9,657 6/19/2016
2.0.45 2,241 6/15/2016
2.0.43 4,396 6/7/2016
2.0.41 2,032 6/6/2016
2.0.37 3,653 6/3/2016
2.0.35 2,506 6/1/2016
2.0.33 1,963 5/30/2016
2.0.32 2,016 5/27/2016
2.0.31 1,896 5/27/2016
2.0.28 15,660 1/29/2016
2.0.27 3,648 1/9/2016
2.0.24 1,863 1/9/2016
2.0.23 10,577 8/23/2015
2.0.21 5,497 7/7/2015
2.0.20 1,881 6/27/2015
2.0.19 1,841 6/27/2015
2.0.18-pre 1,603 6/23/2015
2.0.16-pre 1,664 6/4/2015
2.0.13-pre 1,622 5/24/2015
2.0.12 2,069 5/24/2015
2.0.11-pre 1,630 5/5/2015
2.0.10-pre 1,767 4/25/2015
2.0.9-pre 1,869 3/30/2015
2.0.8-pre 1,582 3/26/2015
2.0.7-pre 1,561 3/15/2015
2.0.6-pre 2,082 3/1/2015
2.0.5-pre 1,711 2/10/2015
2.0.4-pre 1,719 2/9/2015
2.0.3-pre 1,757 2/9/2015
2.0.2-pre 1,697 2/9/2015
2.0.1-pre 1,621 2/1/2015
1.4.139 2,538 1/23/2015
1.4.128 1,912 1/17/2015
1.4.118 1,920 1/13/2015
1.4.113 2,132 1/6/2015
1.4.102 2,348 12/21/2014
1.4.99 2,295 12/18/2014
1.4.97 2,094 12/18/2014
1.4.76 2,117 12/8/2014
1.4.75 2,237 12/7/2014
1.4.39 2,129 11/26/2014
1.4.34 1,996 11/24/2014
1.4.28 1,963 11/24/2014
1.4.27 1,976 11/23/2014
1.4.23 2,111 11/21/2014
1.4.22 2,066 11/21/2014
1.4.21 2,081 11/21/2014
1.4.18 2,225 11/18/2014
1.4.15 2,133 11/4/2014
1.4.14 1,957 10/23/2014
1.4.13 1,906 10/23/2014
1.4.12 1,780 10/12/2014
1.4.11 1,925 10/8/2014
1.4.10 1,965 9/26/2014
1.4.9 1,878 9/17/2014
1.4.8 1,920 9/11/2014
1.4.7 1,844 9/1/2014
1.4.6 1,864 8/31/2014
1.4.5 1,885 8/27/2014
1.4.4 1,856 8/27/2014
1.4.3 1,853 8/25/2014
1.4.2 1,931 8/23/2014
1.4.1 1,820 8/23/2014
1.3.43 2,092 8/4/2014
1.3.42 1,921 7/30/2014
1.3.41 1,828 7/28/2014
1.3.40 1,817 7/26/2014
1.3.39 1,895 7/25/2014
1.3.37 1,887 7/25/2014
1.3.36 1,919 7/20/2014
1.3.35 1,981 7/17/2014
1.3.34 1,973 7/6/2014
1.3.33 1,904 6/30/2014
1.3.30 1,868 6/19/2014
1.3.29 1,864 6/19/2014
1.3.28 1,943 6/19/2014
1.3.27 1,947 6/18/2014
1.3.26 43,447 6/18/2014