Application Insights 的日志未写入跟踪日志

时间:2021-02-04 19:49:45

标签: c# asp.net-core-webapi azure-application-insights serilog

我正在按照此页面 Application Insights Instructions 将 Application Insights (AI) 添加到我的 Web API 服务。我设法让我的服务连接到 AI,并且我能够看到我的服务何时执行 post、get 等。我还通过我的服务进行了日志调用,但它们都没有写入我的 AI 的跟踪日志。< /p>

Traces Log

我确保设置我的 Startup.cs 和 appsettings.json 文件以包含在整个服务中运行 AI 所需的新代码,并且日志数据需要有 AI 抓取日志调试和启动。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{         
    services.AddApplicationInsightsTelemetry();
}

appsettings.json

appsettings.json

日志示例

public async Task ProcessQueueAsync(dBData dbContext)
{
    // _logger is of type ILogger<[INSERT CLASS NAME]>
    _logger.LogDebug("This is a test log by Lotzi11.");
    await ProcessQueueAsyncSingle(dbContext, CancellationToken.None);
}

谁能帮我弄清楚为什么我的日志没有被发送到 AI?

2 个答案:

答案 0 :(得分:1)

您的代码配置和 appsettings.json 是正确的。根据你的设置,我可以在 AI 中看到这些日志。

您应该知道的一件事是,这些数据可能需要几分钟才能到达 AI 服务器。请等待几分钟,比如 5 分钟或更长时间,然后从 azure 门户 -> 应用洞察再次查询这些数据。

这里有一个简单的方法来检查数据是否发送到 AI。在visual studio中,运行项目时,可以在visual studio输出窗口中搜索日志。如果你能在那里找到日志,那么它应该被发送给 AI:

在 Visual Studio 输出窗口中搜索:

enter image description here

如果您仍然无法在 AI 中看到这些日志,您还应该检查您是否在代码中设置了 filtersampling 之类的内容。

答案 1 :(得分:1)

在我努力解决问题的过程中,我发现我的公司使用 Serilog 来处理日志记录,因此我不得不更改我的项目,以便 Serilog 也将日志发送给 AI。我使用以下页面 serilog-sinks-applicationinsights 修改了我的代码。

这让我意识到,即使我遵循了微软关于设置 AI 的说明,我的 ILogger 类也没有正确设置来处理向 AI 发送日志。为了解决这个问题,我修改了 Startup.cs 的构造函数:

    public Startup(IHostEnvironment environment, IConfiguration configuration)
    {
        var env = new Environment(environment.EnvironmentName);

        _systemConfiguration = new SystemConfiguration(env, configuration);
        _systemConfiguration.Validate();

        Log.Logger = new LoggerConfiguration().Enrich.FromLogContext().WriteTo.ApplicationInsights(_systemConfiguration.BaseConfiguration["APPINSIGHTS_INSTRUMENTATIONKEY"], TelemetryConverter.Traces).CreateLogger();
        using var provider = new SerilogLoggerProvider(Log.Logger);            
        _logger = provider.CreateLogger(nameof(Startup));
    }

将 AI 添加到 Log.Logger 后,我的日志开始显示在我的 AI 页面中。

相关问题