Search code examples
c#asp.net-coreazure-application-insightsserilogserilog-aspnetcore

Not able to write logs to Azure Application Insights in Controller using Serilog


I have a .net6 web API, I am trying to write logs to Azure application insights. It works when I try to write in Program.cs. But it's not writing when I am trying to write in the Controller action method.

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", false, true)
            .Build();
        var logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        logger.Information("Hello, world!!!!!");

            var builder = WebApplication.CreateBuilder(args);

Controller:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        _logger.LogInformation("Info");
        _logger.LogTrace("Trace");
        _logger.LogCritical("Critical");
        _logger.LogDebug("Debug");
        _logger.LogError("Error");
        _logger.LogWarning("Warning");

        Log.Information("Information!");
        Log.Warning("Warning!");
        Log.Error("Error!");
        Log.Debug("Debug!");

        Log.Logger.Error("Information!!");
        Log.Logger.Warning("Warning!!");
        Log.Logger.Error("Error!!");
        Log.Logger.Debug("Debug!!");
        Log.Logger.Warning("Warning!!");

Appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [
      "Serilog.Sinks.ApplicationInsights"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "ApplicationInsights",
        "Args": {
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext" ],
    "Properties": {
      "Application": "Sample"
    }
  }
}

I have set my connection string in the environment variable.

These are the Nuget packages along with the versions.

enter image description here

Azure app insights

enter image description here


Solution

    • As you mentioned, Even I have set Application Insights Connection String in Visual Studio Environment Variable.

    enter image description here

    • Initially with your code Iam able to log only the messages from Program.cs file.

    enter image description here

    • After making few changes in Program.cs only Iam able to see the messages from Controller.

    Progarm.cs file:

    using Serilog;
    using Serilog.Sinks.ApplicationInsights.TelemetryConverters;
    
    var ConnStr = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
    var configuration = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json", false, true)
               .Build();
    var logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .WriteTo.ApplicationInsights(ConnStr, new TraceTelemetryConverter())
        .CreateLogger();
    
    logger.Information("Hello, world ");
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Logging.AddSerilog(logger);
    
    var app = builder.Build();
    

    Message from Program.cs:

    enter image description here

    Message from Controller:

    enter image description here

    enter image description here

    My Controller.cs:

    using Microsoft.AspNetCore.Mvc;
    using Serilog;
    
    namespace SerilogInsights.Controllers
    {
        [ApiController]
        [Route("[controller]")]
        public class WeatherForecastController : ControllerBase
        {
            private static readonly string[] Summaries = new[]
            {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
    
            private readonly ILogger<WeatherForecastController> _logger;
    
            public WeatherForecastController(ILogger<WeatherForecastController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet(Name = "GetWeatherForecast")]
            public IEnumerable<WeatherForecast> Get()
            {
                _logger.LogInformation("Info..");
                _logger.LogTrace("Trace from Controller");
                _logger.LogCritical("Critical trace");
                _logger.LogDebug("Debug message logs");
                _logger.LogError("Error message");
                _logger.LogWarning("Warning message");
    
                Log.Information("Information!");
                Log.Warning("Warning!");
                Log.Error("Error!");
                Log.Debug("Debug!...");
    
                Log.Logger.Error("Information!! ...");
                Log.Logger.Warning("Warning!!");
                Log.Logger.Error("Error!!");
                Log.Logger.Debug("Debug!!");
                Log.Logger.Warning("Warning!!");
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                })
                .ToArray();
            }
        }
    }
    

    My .csproj file:

    <Project Sdk="Microsoft.NET.Sdk.Web">
    
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Serilog" Version="2.12.0" />
        <PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
        <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
      </ItemGroup>
    
    </Project>