无法使用 Serilog 将日志写入控制器中的 Azure Application Insights

问题描述 投票:0回答:2

我有一个 .net6 web API,我正在尝试将日志写入 Azure 应用程序见解。当我尝试在 Program.cs 中编写时它起作用了。但是当我尝试在 Controller 操作方法中写入时,它并没有写入。

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

控制器

[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"
    }
  }
}

我已经在环境变量中设置了我的连接字符串。

这些是 Nuget 包和版本。

Azure 应用见解

c# asp.net-core azure-application-insights serilog serilog-aspnetcore
2个回答
0
投票
  • 正如您所提到的,即使我已经在 Visual Studio 环境变量中设置了
    Application Insights Connection String

enter image description here

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

enter image description here

  • 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

enter image description here

消息来自

Controller

enter image description here

enter image description here

我的

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>


0
投票

在我看来,

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

如果您遵循Configuration Basics - 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;
// 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();
}
© www.soinside.com 2019 - 2024. All rights reserved.