1

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

8
  • You have set connection string in environment variables and adding configuration from appsettings.json. Please check the code in program.cs Commented Apr 13, 2023 at 15:10
  • You are not using the retrieved value anywhere. Commented Apr 13, 2023 at 15:11
  • 1
    @Harshitha I have removes that code. that was just to check whether I am getting the value of the environment variable for debugging purposes. And If you notice I am able to see Hello, World!!!!! in logs, but not the ones which are written in the controller. hope it makes clear now. Commented Apr 13, 2023 at 15:34
  • Hope you are executing the correct httpget method. Commented Apr 13, 2023 at 15:43
  • @Harshitha yes, I have put breakpoint and I’m able to hit Commented Apr 13, 2023 at 16:38

2 Answers 2

2
  • 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>

Sign up to request clarification or add additional context in comments.

14 Comments

Thank you I’ll try with your code. One thing can we use InstrumentationKey in place of ConnectionString?
Yes,we can use Instrumentation key as well.But in MsDoc it says Instrumentation key is going to be deprecated.
@SPT I understand your concern. I am yet to try the solution provided.
@Harshitha I have made the changes as you suggested. But it is still not writing logs from the controller. Can you show me your controller code?
I have not made any chanegs to the default code, just added the logs same as your's.Please check the edit in the answer.
|
0

It seems to me that the code in Program.cs doesn't configure Serilog properly.

If you follow Configuration Basics - Serilog Wiki you must set Serilog.Log to a logger.

So try to change

var logger = new LoggerConfiguration()
  .ReadFrom.Configuration(configuration)
  .CreateLogger();

to

Log.Logger = new LoggerConfiguration()
  .ReadFrom.Configuration(configuration)
  .CreateLogger();

In this way Log methods will work. But, you must use Log class and couldn't use ILogger injection, since Serilog is not set as "the default logger" method.

I suggest to use Serilog.AspNetCore package and setup your application as written in the README.

using Serilog;
// This provide logger functionality  for startup
Log.Logger = new LoggerConfiguration() 
    .WriteTo.Console()
    .CreateLogger();

try
{
    Log.Information("Starting web application");

    var builder = WebApplication.CreateBuilder(args);

    builder.Host.UseSerilog(); 

    // ...
    
    var app = builder.Build();

    // ...
    
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.