简体   繁体   中英

Data not sent to App Insights from ILogger in Startup

I have enabled the app insights logging in the application. From other places like controller, other classes I am able to use logger and the data is sent to application insights but in startup I tried to send the data to AI but its not pushing the data to AI. I am not getting any error, Instance is created but the data is not pushed to AI. Here is my startup

public class Startup
{
    private readonly ILogger _logger;
    public Startup(ILogger<Startup> logger)
    {
        _logger = logger;
    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddLogging(log =>
        {
            log.AddApplicationInsights();
        });
        services.AddApplicationInsightsTelemetry();
        _logger.LogError("something");
    }
}

appsettings.json

"Logging": {
  "ApplicationInsights": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "logLevel": { "default": "Information" }
}

Reference App startup in ASP.NET Core

Only the following service types can be injected into the Startup constructor when using the Generic Host (IHostBuilder):

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration

... Most services are not available until the Configure method is called.

As you are actually registering the logger within the Startup itself, it wont be ready by the time the class is instantiated.

Consider moving the logger registration out so that it is there by the time Startup is initialized.

public class Program {
    public static void Main(string[] args) {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) => {
                services.AddApplicationInsightsTelemetry();
            })
            .ConfigureLogging(logging => {
                logging.AddApplicationInsights();
            })
            .ConfigureWebHostDefaults(webBuilder => {
                webBuilder.UseStartup<Startup>(); 
            });
}

In Startup , the desired logging behavior should now be available

public class Startup {
    private readonly ILogger _logger;

    public Startup(ILogger<Startup> logger) {
        _logger = logger;
    }

    public void ConfigureServices(IServiceCollection services) {

        _logger.LogError("something");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM