You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET6 Web API使用Serilog无法在Controller写入Azure Application Insights日志

问题:.NET6 Web API中Serilog日志在Program.cs生效但Controller中不生效

我有一个.NET6 Web API项目,尝试通过Serilog将日志写入Azure Application Insights。在Program.cs中写入日志能正常生效,但在Controller的Action方法中写入日志却无法成功。

以下是相关代码及配置:

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

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

已在环境变量中设置了Azure Application Insights连接字符串,同时附上使用的NuGet包版本截图及Azure Application Insights截图。

内容的提问来源于stack exchange,提问作者Vivek Nuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:52:40