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

ASP.NET Core中Serilog与ApplicationInsights 3.x整合问题咨询

问题:Serilog与Application Insights 3.x集成时的日志提供者重复问题

原本我使用Serilog输出控制台日志,并通过Serilog.Sink.ApplicationInsights包将日志写入Application Insights。但现在需要升级至Serilog Sink不支持的Application Insights 3.x版本。

查阅文档后,我计划让Serilog仅输出至控制台Sink,设置writeToProviders=true以让其他组件处理Application Insights日志。但添加services.AddApplicationInsightsTelemetry()后,Serilog的ILoggerFactory实现中所有LogProvider都出现重复。

复现问题的最小化代码

using System.Globalization;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Serilog;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.FromLogContext()
    .WriteTo.Console(formatProvider: CultureInfo.InvariantCulture)
    .CreateBootstrapLogger();

Log.Information("Starting Web MinimalTest...");
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddEnvironmentVariables();

// Add services to the container.
IServiceCollection services = builder.Services;

services.RemoveAll<ILoggerProvider>();
services.AddSerilog((serviceProvider, loggerConfiguration) =>
{
    loggerConfiguration
        .WriteTo.Console(
            outputTemplate:
            "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext:1} {Message:lj} {Exception}{NewLine}",
            formatProvider: CultureInfo.InvariantCulture);
}, writeToProviders: true);

services.AddApplicationInsightsTelemetry();

WebApplication app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

string[] summaries = ["Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"];

app.MapGet("/weatherforecast", (ILogger<Program> logger) =>
{
    logger.LogInformation("Interesting info is {Number}", 42);

    WeatherForecast[] forecast = Enumerable.Range(1, 5).Select(index =>
            new WeatherForecast
            (
                DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                Random.Shared.Next(-20, 55),
                summaries[Random.Shared.Next(summaries.Length)]
            ))
        .ToArray();
    return forecast;
});

object? factory = app.Services.GetService(typeof(ILoggerFactory));
// factory._providerCollection.Count is 4 here when it should be 2

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(this.TemperatureC / 0.5556);
}

我的解决方案代码

我通过仅将Serilog LoggerProvider添加至Microsoft.Extensions.Logging框架的方式解决了问题,代码如下:

// .... 
// Add services to the container.
IServiceCollection services = builder.Services;

Logger logger = new LoggerConfiguration()
    .WriteTo.Console(
        outputTemplate:
        "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext:1} {Message:lj} {Exception}{NewLine}",
        formatProvider: CultureInfo.InvariantCulture)
    .CreateLogger();

services.AddLogging(b =>
{
    b.ClearProviders();
    b.AddSerilog(logger);
});

// Register the diagnostic context (concrete type is required by UseSerilogRequestLogging,
// the interface is used by usercode).
var diagnosticContext = new DiagnosticContext(logger);
services.AddSingleton(diagnosticContext);
services.AddSingleton<IDiagnosticContext>(diagnosticContext);

services.AddApplicationInsightsTelemetry();
// ...

由于代码中需要使用DiagnosticContext,我手动注册了该组件(原本由IServiceCollection.AddSerilog()扩展方法自动添加)。

请问这种Serilog与Application Insights的使用方式是否正确?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.06 05:13:10