Get an ILogger instance for App Insights from ServiceCollection in a WebForms .NET Framework application

Wadhwani, Jatin 0 Reputation points
2023-01-31T12:10:20.45+00:00

We want to get an ILogger instance so that it can be passed to other library. We tried below, but the ILogger instance does not log into Application Insights. It logs into Event Viewer successfully.

We have added the necessary packages i.e. Microsoft.Extensions.Logging and Microsoft.Extensions.Logging.ApplicationInsights

Is there no way, we can get an ILogger instance from ServiceCollection for AppInsights?

var serviceCollection = new ServiceCollection();
        serviceCollection.AddLogging(builder => builder
        .AddFilter("Default", LogLevel.Information)
        .AddFilter("Microsoft", LogLevel.Warning)
        .AddFilter("System", LogLevel.Warning)
        .AddEventLog(config => { config.LogName = "Pages"; config.SourceName = "Pages"; })
        .AddApplicationInsights(telemetry =>
        telemetry.ConnectionString = "my-key",
        options => options = new ApplicationInsightsLoggerOptions()));


        var serviceProvider = serviceCollection.BuildServiceProvider();
        var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
        var logger = loggerFactory.CreateLogger("my-logger");
        logger.LogInformation("Hi");
ASP.NET Web Forms
ASP.NET Web Forms
A part of the ASP.NET web application framework that can be used to create ASP.NET web applications.
458 questions
No comments
{count} votes