使用 LoggerFactory 登录 Application Insights for .NET Core 2.1 控制台应用程序

San*_*eth 0 .net console-application azure azure-application-insights asp.net-core-2.1

我有一个 .NET Core 2.1 控制台应用程序。我已经添加了所需的所有 Nuget 包。

private static IConfiguration Configuration { get; set; }
static void Main(string[] args)
{
    ServiceCollection services = new ServiceCollection();
    ConfigureServices(services);
    var serviceProvider = services.BuildServiceProvider();
    var logger = serviceProvider.GetService<ILoggerFactory>()
        .CreateLogger<Program>()
    var service = serviceProvider.GetService<TestClass>();
    service.TimmerTriggerTask();
}

private static void ConfigureServices(IServiceCollection services)
{
    IConfiguration config = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", true, true)
            .Build();
    services.AddApplicationInsightsTelemetry("8028437c-1111-2222-8293-2cf3f3f106a8"); //instrumentation key
    services.AddLogging(builder => builder.AddConsole());
}

TestClass.cs
public class TestClass
{
    private readonly ILogger<TestClass> _logger;

    public TestClass(ILogger<TestClass> logger)
    {
        Console.WriteLine("Ctor");
        _logger = logger;
    }

    public void TimmerTriggerTask()
    {
        Console.WriteLine("Timer");
    //LOG BELOW IN APPLICATION INSIGHTS
        _logger.LogTrace("Hello World");
        _logger.LogInformation(DateTime.Now.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要在 Application Insights 中记录所有信息和异常。希望将 loggerfactory 与 applicationInsights 集成。

我正在寻找我们可以在 .NET Core Web 应用程序中做的事情

WebHost.CreateDefaultBuilder(args).UseApplicationInsights()
loggerFactory.AddApplicationInsights(app.ApplicationServices, defaultLogLevel);
Run Code Online (Sandbox Code Playgroud)

请帮助我如何使用记录器类登录 applicationinsights。

如果我所做的不正确,请提供替代解决方案。

小智 5

LoggerFactory.AddApplicationInsights 已被弃用。添加对Microsoft.Extensions.Logging.ApplicationInsights的引用并使用以下代码。您可以在此处找到 Microsoft 的完整示例。

    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();

        // Channel is explicitly configured to do flush on it later.
        var channel = new InMemoryChannel();
        services.Configure<TelemetryConfiguration>(
            (config) =>
            {
                config.TelemetryChannel = channel;
            }
        );

        services.AddLogging(builder =>
        {
            builder.AddConsole();
            builder.AddApplicationInsights("[AI Instrumentation Key here]");
        });

        var provider = services.BuildServiceProvider();
        var logger = provider.GetService<ILogger<Program>>();

        logger.LogInformation("This will show up in Application Insights"); 

        // Explicitly call Flush() followed by sleep is required in Console Apps.
        // This is to ensure that even if application terminates, telemetry is sent to the back-end.
        channel.Flush();
        Thread.Sleep(1000);
    }
Run Code Online (Sandbox Code Playgroud)

您可以使用日志消息模板添加自定义维度以实现结构化日志记录。

public void DoTheThings()
{ 
    var id = 12345;
    var duration = 300;

    logger.LogInformation(
        "Did the things for Id: {actionId} in {durationMs}ms. Params: {p2}, {p1}", 
        id, duration, "param1", "param2");
}

Run Code Online (Sandbox Code Playgroud)

这将在 Application Insights 中生成一条跟踪消息:

"Did the things for Id: 12345 in 300ms.  Params: param1, param2"
Run Code Online (Sandbox Code Playgroud)

和自定义尺寸包括:

{ 
    "actionId": "12345",
    "durationMS": "300",
    "p2" : "param1",
    "p1" : "param2"
}
Run Code Online (Sandbox Code Playgroud)

请注意:

  1. 消息模板不是插字符串。
  2. customDimensions 中的属性名称基于消息模板而不是参数。
  3. 模板属性按顺序绑定到参数,而不是按名称。