When it comes to building modern .NET applications in the cloud, observability is key. Tracing errors, monitoring performance, and analyzing application behavior in production are no longer luxuries but essentials. If you’re using Azure, then Application Insights is one of the best tools to achieve this. And if you pair it with Serilog, you get an incredibly powerful and easy-to-implement logging solution.

In this post, I’ll show you how simple it is to configure Serilog to log directly to Application Insights. Whether you’re running a production system or debugging your app in staging, this integration will save you a ton of headaches and make you a logging pro.


Why Log to Application Insights?
#

Application Insights is more than just a logging tool. It provides:

  • Centralized Logging: All your logs in one place, accessible from the Azure Portal.
  • Telemetry Integration: Track dependencies, requests, and custom events.
  • Error Tracing: Easily correlate exceptions with logs for faster debugging.
  • Real-Time Analytics: Use the powerful KQL (Kusto Query Language) to analyze logs and performance metrics.

By leveraging Serilog, you can take advantage of structured logging and Application Insights telemetry capabilities with minimal effort.


Getting Started
#

Step 1: Install Required NuGet Packages
#

To set up Serilog for Application Insights, you’ll need the following packages:

dotnet add package Serilog.Sinks.Console dotnet add package Serilog.Extensions.Hosting dotnet add package Serilog.Sinks.ApplicationInsights dotnet add package Microsoft.ApplicationInsights.AspNetCore

1
2
3
4
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Sinks.ApplicationInsights
dotnet add package Microsoft.ApplicationInsights.AspNetCore

To have an easy to use integration in our .NET9 console application, we are also installing some other packages:

1
2
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.DependencyInjection

These packages provide the foundation for integrating Serilog with a .NET 9 console application. The Microsoft.Extensions.Hosting and Microsoft.Extensions.DependencyInjection packages simplify the creation and management of hosted services and dependency injection.

Step 2: Configure Application Insights in Azure
#

  1. Navigate to the Azure Portal and create a new Application Insights resource for your application.
  2. Note down the Instrumentation Key or Connection String from the resource overview.
  • The Connection String is the preferred method for modern applications.

Note: If you’re deploying your application to an Azure WebApp with Application Insights enabled, you don’t need to specify a connection string in your code. The Azure runtime automatically provides the necessary integration, simplifying your setup and eliminating the need to manage secrets.

Step 3: Configure Serilog for Application Insights
#

Let’s integrate Serilog with Application Insights in a .NET console application. Here’s how you can set it up:

Create the Logger
#

Add the following code at the very start of your Program.cs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.ApplicationInsights(
        connectionString: "Your Application Insights Connection String", 
        telemetryConverter: TelemetryConverter.Traces) 
    .CreateLogger();
try
{
    Log.Information("Starting the application");
    // Create the host builder with logging configured
    var builder = Host.CreateApplicationBuilder(args);
    builder.Services.AddHostedService<MyCustomHostedService>();
    builder.Services.AddLogging(logging =>
    {
        logging.ClearProviders(); // Remove default logging
        logging.AddSerilog(); // Add Serilog as the logging provider
    });
    var app = builder.Build();
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

How This Works
#

  • Enrich.FromLogContext(): Adds useful context like correlation IDs to your logs.
  • WriteTo.ApplicationInsights(): Directs logs to Application Insights using the provided connection string.
  • TelemetryConverter.Traces: Converts Serilog log messages into traces for Application Insights.

Step 4: Add a Sample Hosted Service
#

For demonstration, let’s create a simple hosted service that generates logs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public partial class MyCustomHostedService(ILogger<MyCustomHostedService> logger) : IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Logger.StartingMyCustomHostedService(logger);
        Logger.WarningMessage(logger);
        Logger.ErrorMessage(logger);
        return Task.CompletedTask;
    }
    public Task StopAsync(CancellationToken cancellationToken)
    {
        Logger.StoppingMyCustomHostedService(logger);
        return Task.CompletedTask;
    }

    private static partial class Logger
    {
        [LoggerMessage(0, LogLevel.Information, "Starting MyCustomHostedService")]
        public static partial void StartingMyCustomHostedService(ILogger logger);
        
        [LoggerMessage(1, LogLevel.Warning, "This is a warning message")]
        public static partial void WarningMessage(ILogger logger);
        
        [LoggerMessage(2, LogLevel.Error, "This is an error message")]
        public static partial void ErrorMessage(ILogger logger);
        
        [LoggerMessage(3, LogLevel.Information, "Stopping MyCustomHostedService")]
        public static partial void StoppingMyCustomHostedService(ILogger logger);
    }
}

Step 5: Testing Your Setup
#

Run the application and generate some logs. Then:

  1. Navigate to your Application Insights resource in Azure.
  2. Open the Logs section and use the query below to view your logs:

traces | where timestamp > ago(1h) | order by timestamp desc

You’ll see all your Serilog logs right there, complete with levels and timestamps.


Enhancing with Structured Logging
#

One of Serilog’s strengths is its support for structured logging. Instead of writing plain text, you can log objects and key-value pairs, making it easier to query and analyze logs.

For example:

1
Logger.LogInformation("User {UserId} has logged in from IP {IpAddress}", userId, ipAddress);

This will log as structured data, which you can filter and analyze more effectively in Application Insights.


Step 6: Scaling with Configuration
#

For production use, you should configure Serilog via appsettings.json. This allows you to change logging levels and sinks without modifying your code.

Here’s a simple example of an appsettings.json:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.ApplicationInsights" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "connectionString": "Your Application Insights Connection String",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.Traces"
        }
      }
    ]
  }
}

Load this configuration into your application:

1
2
3
4
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

Final Thoughts
#

Logging to Application Insights with Serilog is a game-changer. It simplifies error tracing, improves debugging, and integrates seamlessly into Azure’s ecosystem. By combining Serilog’s structured logging capabilities with Application Insights, you’re setting your application up for success in any environment, especially production.

So, the next time you deploy to Azure, don’t just log — log smart. Set up Serilog with Application Insights and give yourself the gift of easier debugging and better observability.

Go ahead and implement this in your next project! Future you will thank you.