3
votes

I've got a .net core console application (not AspNetCore), and I want to add app insights logging that will push out the trace logs to app insights. I have tried using Microsoft.ApplicationInsights.AspNetCore, but when I do:

 factory.AddApplicationInsights(serviceProvider);

it throws an error saying it can't find the hosting environment

Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers.AspNetCoreEnvironmentTelemetryInitializer'.

presumably because this is not an AspNetCore app, but just a pure console app.

Is there a way I can get trace logging pushed to App Insights from within my .net core console app?

2
Use Microsoft.ApplicationInsights as described in github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/…. - Mats Björkman Eldh
Thanks, that looks like I'd have to create a custom logger and then in that logger call the underlying App Insights API. Which I can do if necessary, but I thought there would one available already. - Slicc
docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger There is a new Microsoft.Extensions.Logging.ApplicationInsights package available which works in console apps. - cijothomas

2 Answers

5
votes

Actually, faced same problem and finally resolved it looking inside AddApplicationInsights source code. The trick is that you had to register TelemetryClient manually to the container to make this stuff work for console application:

  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");