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.
Azure app insights






