将应用程序见解跟踪日志记录添加到 .net core 控制台应用程序

2024-04-13

我有一个 .net core 控制台应用程序(不是 AspNetCore),我想添加应用程序见解日志记录,将跟踪日志推送到应用程序见解。我尝试过使用 Microsoft.ApplicationInsights.AspNetCore,但是当我这样做时:

 factory.AddApplicationInsights(serviceProvider);

它抛出一个错误,说找不到托管环境

尝试激活“Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer”时无法解析类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务。

大概是因为这不是一个 AspNetCore 应用程序,而只是一个纯粹的控制台应用程序。

有没有办法可以将跟踪日志记录从我的 .net core 控制台应用程序中推送到 App Insights?


实际上,遇到了同样的问题,并最终通过查看 AddApplicationInsights 源代码解决了它。诀窍是您必须手动将 TelemetryClient 注册到容器中才能使这些东西适用于控制台应用程序:

  var telemetryClient = new TelemetryClient(new TelemetryConfiguration()
        {
            InstrumentationKey = config.GetValue("ApplicationInsights:InstrumentationKey")
        });

        services.AddSingleton(x => telemetryClient);

        var provider = services.BuildServiceProvider();

        loggerFactory.AddApplicationInsights(provider, LogLevel.Information);
        var logger = loggerFactory.CreateLogger<Program>();

        logger.LogInformation("Test");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将应用程序见解跟踪日志记录添加到 .net core 控制台应用程序 的相关文章

随机推荐