Unable to write logs to Azure Application Insights in Controller using Serilog.

huangapple go评论72阅读模式
英文:

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

问题

你有一个.NET 6 Web API,尝试将日志写入Azure应用程序洞察。当我尝试在Program.cs中写入时,它有效。但是当我尝试在Controller操作方法中写入时,它不起作用。

以下是你的Program.cs部分:

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"的JSON文件,其中包含了日志配置信息。

请注意,你需要确保配置正确,并且在Controller中,你正在使用_logger来记录日志。如果日志仍然不起作用,请检查应用程序洞察的配置和连接字符串。

英文:

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(&quot;appsettings.json&quot;, false, true)
            .Build();
        var logger = new LoggerConfiguration()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

        logger.Information(&quot;Hello, world!!!!!&quot;);

            var builder = WebApplication.CreateBuilder(args);

Controller:

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

    private readonly ILogger&lt;WeatherForecastController&gt; _logger;

    public WeatherForecastController(ILogger&lt;WeatherForecastController&gt; logger)
    {
        _logger = logger;
    }

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

        Log.Information(&quot;Information!&quot;);
        Log.Warning(&quot;Warning!&quot;);
        Log.Error(&quot;Error!&quot;);
        Log.Debug(&quot;Debug!&quot;);

        Log.Logger.Error(&quot;Information!!&quot;);
        Log.Logger.Warning(&quot;Warning!!&quot;);
        Log.Logger.Error(&quot;Error!!&quot;);
        Log.Logger.Debug(&quot;Debug!!&quot;);
        Log.Logger.Warning(&quot;Warning!!&quot;);

Appsettings.json:

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

I have set my connection string in the environment variable.

These are the Nuget packages along with the versions.

Unable to write logs to Azure Application Insights in Controller using Serilog.

Azure app insights

Unable to write logs to Azure Application Insights in Controller using Serilog.

答案1

得分: 1

以下是您提供的翻译:

  • 正如您提到的,即使我在Visual Studio环境变量中设置了“Application Insights Connection String”。

  • 最初,使用您的代码,我只能记录来自“Program.cs”文件的消息。

  • 在“Program.cs”中进行了一些更改后,我才能看到来自“Controller”的消息。

“Progarm.cs”文件:

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();

“Program.cs”中的消息:

“Controller”中的消息:

“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();
        }
    }
}

我的.csproj文件:

<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>
英文:
  • As you mentioned, Even I have set Application Insights Connection String in Visual Studio Environment Variable.

Unable to write logs to Azure Application Insights in Controller using Serilog.

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

Unable to write logs to Azure Application Insights in Controller using Serilog.

  • 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(&quot;APPLICATIONINSIGHTS_CONNECTION_STRING&quot;);
var configuration = new ConfigurationBuilder()
           .AddJsonFile(&quot;appsettings.json&quot;, false, true)
           .Build();
var logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .WriteTo.ApplicationInsights(ConnStr, new TraceTelemetryConverter())
    .CreateLogger();

logger.Information(&quot;Hello, world &quot;);

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddSerilog(logger);

var app = builder.Build();

Message from Program.cs:

Unable to write logs to Azure Application Insights in Controller using Serilog.

Message from Controller:

Unable to write logs to Azure Application Insights in Controller using Serilog.

Unable to write logs to Azure Application Insights in Controller using Serilog.

My Controller.cs:

using Microsoft.AspNetCore.Mvc;
using Serilog;

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

        private readonly ILogger&lt;WeatherForecastController&gt; _logger;

        public WeatherForecastController(ILogger&lt;WeatherForecastController&gt; logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = &quot;GetWeatherForecast&quot;)]
        public IEnumerable&lt;WeatherForecast&gt; Get()
        {
            _logger.LogInformation(&quot;Info..&quot;);
            _logger.LogTrace(&quot;Trace from Controller&quot;);
            _logger.LogCritical(&quot;Critical trace&quot;);
            _logger.LogDebug(&quot;Debug message logs&quot;);
            _logger.LogError(&quot;Error message&quot;);
            _logger.LogWarning(&quot;Warning message&quot;);

            Log.Information(&quot;Information!&quot;);
            Log.Warning(&quot;Warning!&quot;);
            Log.Error(&quot;Error!&quot;);
            Log.Debug(&quot;Debug!...&quot;);

            Log.Logger.Error(&quot;Information!! ...&quot;);
            Log.Logger.Warning(&quot;Warning!!&quot;);
            Log.Logger.Error(&quot;Error!!&quot;);
            Log.Logger.Debug(&quot;Debug!!&quot;);
            Log.Logger.Warning(&quot;Warning!!&quot;);
            return Enumerable.Range(1, 5).Select(index =&gt; new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

My .csproj file:

&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Serilog&quot; Version=&quot;2.12.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Serilog.AspNetCore&quot; Version=&quot;6.1.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Serilog.Sinks.ApplicationInsights&quot; Version=&quot;4.0.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Swashbuckle.AspNetCore&quot; Version=&quot;6.2.3&quot; /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;

答案2

得分: 0

以下是您要的中文翻译:

似乎 Program.cs 中的代码没有正确配置 Serilog。

如果您按照 配置基础 - Serilog Wiki 的说明,您必须将 Serilog.Log 设置为日志记录器。

因此,请尝试将以下代码:

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

更改为:

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

这样,Log 方法将正常工作。但是,您必须使用 Log 类,并且不能使用 ILogger 注入,因为 Serilog 没有设置为“默认日志记录器”方法。

我建议使用 Serilog.AspNetCore 包,并按照 README 中的说明设置您的应用程序。

using Serilog;
// 为启动提供日志记录功能
Log.Logger = new LoggerConfiguration() 
    .WriteTo.Console()
    .CreateLogger();

try
{
    Log.Information("启动 Web 应用程序");

    var builder = WebApplication.CreateBuilder(args);

    builder.Host.UseSerilog(); 

    // ...

    var app = builder.Build();

    // ...

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序意外终止");
}
finally
{
    Log.CloseAndFlush();
}

希望这有助于您的代码配置。

英文:

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(&quot;Starting web application&quot;);

    var builder = WebApplication.CreateBuilder(args);

    builder.Host.UseSerilog(); 

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

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

huangapple
  • 本文由 发表于 2023年4月13日 18:56:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定