IHostedService控制台应用程序中的应用程序见解

时间:2018-08-27 14:55:27

标签: .net-core console-application azure-application-insights asp.net-core-hosted-services

我正在尝试使用IHostedService在控制台应用程序中启用Application Insights(目前,这是一个简单的控制台应用程序,以后我们将以WebJob的形式在容器中运行)。

据我所知,在以下代码中,到目前为止,我们还没有扩展名来将全局Application Insights注册为 ILogger 的实现:

  public static class Program
    {
        public static Task Main(string[] args)
        {
            var hostBuilder = new HostBuilder()
                .ConfigureHostConfiguration(config =>
                {
                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddJsonFile("appsettings.json", optional: false);
                    config.AddEnvironmentVariables();
                })
                .ConfigureLogging((context, logging) =>
                {
                    logging.AddConfiguration(context.Configuration.GetSection("Logging"));

                    if (context.HostingEnvironment.IsDevelopment())
                    {
                        logging.AddConsole();
                    }
                    else
                    {
                        //TODO: register ApplicationInsights
                    }
                });

            return hostBuilder.RunConsoleAsync();
        }
    }

到目前为止,我发现潜在地,我应该能够使用记录器的自定义实现来设置所有内容,即public class ApplicationInsightsLogger : ILogger,然后...在容器中注册它,以便DI可以解决它。

这是正确的方向吗?

1 个答案:

答案 0 :(得分:0)

我做了一个扩展,可以从IHostIWebHost中使用:

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.ApplicationInsights;

public static class LoggingBuilderExtensions
{
    public static ILoggingBuilder AddLogging(this ILoggingBuilder loggingBuilder)
    {
        loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
        loggingBuilder.AddAzureWebAppDiagnostics();
        loggingBuilder.AddApplicationInsights();
        return loggingBuilder;
    }
}

由于我不在上下文中发送(HostBuilderContextWebHostBuilderContext),因此可以在以下两种应用程序类型中使用它:

new HostBuilder().ConfigureLogging(loggingBuilder => loggingBuilder.AddLogging())

WebHost.CreateDefaultBuilder().ConfigureLogging(loggingBuilder => loggingBuilder.AddLogging())

如果您需要上下文中的特定属性(例如环境类型),则可以提取该属性并将其作为参数发送给扩展。

这里是参考:https://github.com/Microsoft/ApplicationInsights-dotnet-logging/blob/develop/src/ILogger/Readme.md

相关问题