Search code examples
.net-coreconsole-applicationazure-application-insightsasp.net-core-hosted-services

Application Insights in IHostedService console application


I am trying to enable Application Insights in a console application using IHostedService (for the moment, it's a simple console application which we run as WebJob, in future in containers).

As far as my knowledge goes, in the following code, so far we do not have any extension to register globally Application Insights as an implementation of 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();
        }
    }

So far, I found out that potentially, I should be able to set everything up using custom implementation of the logger, i.e. public class ApplicationInsightsLogger : ILogger, and then... register it in the container so that DI resolves it.

Is this the right direction?


Solution

  • I made an extension that I could use from either an IHost or an IWebHost:

    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;
        }
    }
    

    Since I'm not sending in the context (HostBuilderContext or WebHostBuilderContext), I can use it in either app type like this:

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

    or

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

    If you needed a specific property from the context (like environment type), you could extract that and send it in as a parameter to the extension.

    Here's a reference: https://github.com/Microsoft/ApplicationInsights-dotnet-logging/blob/develop/src/ILogger/Readme.md