Simplifying ASP.NET Core 8 Logging with Serilog and AppInsight

Introduction

Logs are an important aspect of application development, allowing you to monitor and troubleshoot problems and bugs in your application. Serilog is popular with developers because it provides structured logging, allowing issues to be identified and resolved quickly.

Serilog is a diagnostic logging library designed specifically for .NET applications. It is a simple, flexible, and powerful approach to logging application events, errors, and other relevant information. One of Serilog’s key strengths is its support for structured logging, allowing developers to log rich, structured data rather than just plain text messages.

To learn more about Serilog's key features in detail, you can visit the previous article here.

In this article, we will learn application logging in ASP.NET Core Web API project using Serilog with sink AppInsights.

Now, let’s move to implementing application logging with Verilog with steps.

Step 1. Create a new ASP.NET Core Web API application .NET8 or use your existing project where you need to use Serilog logging with AppInsights.

ASP.Net

Give the project name, select the location of the project, and Click on Next.

Project

Select project framework: .NET 8, as depicted below.

 Project framework

Step 2. Install the following packages in your project from the NuGet package manager.

  • Serilog
  • Serilog.AspNetCore
  • Serilog.Sinks.File
  • Serilog.Sinks.ApplicationInsights

Step 3. After the installation of the necessary packages, we will need to configure Serilog in the appsetting.json file. Implementing logging with Verilog in local files and Appinsights is almost similar. However, there are some changes, such as in Using, Write To, and so on, which you can see in the below appsetting.json file.

Note. You need to have an Azure subscription and have already created application insights for this configuration to work.

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

If you want to log in to the local file, you can refer to the previous article here.

Step 4. In the Program.cs, we will add the Serilog configuration.

builder.Host.UseSerilog((context, configuration) =>
    configuration.ReadFrom.Configuration(context.Configuration));

Step 5. Then, above the App.Run() write Serilog middleware.

app.UseSerilogRequestLogging();

Step 6. Then, we can now log in to any C# class.

Below is an example of logging in TestController.

using Microsoft.AspNetCore.Mvc;
namespace SampleLogger.Controllers;
[ApiController]
[Route("[controller]")]
public class TestController :  ControllerBase
{
    private readonly ILogger<TestController> _logger;
    public TestController(ILogger<TestController> logger)
    {
        _logger = logger;
    }
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IActionResult Get()
    {
        _logger.LogInformation("Test Controller called!");
        return Ok();
    } 
}

Now, we can run the application and check the logs in application insights.

Conclusion

Developers can improve debugging, monitoring, and system maintenance by integrating Serilog to generate more detailed and actionable log data. Serilog’s structured logging capabilities make it easier to analyze and visualize logs, making it essential for modern applications. By using Serilog, you can significantly improve your application’s traceability, reliability, and overall performance. In this article, we learned how to log applications with Serilog and Application insights. I hope you find it helpful.

Reference


Similar Articles