ILogger to Application Insights

16,942

update:

If you have the latest package Microsoft.Extensions.Logging.ApplicationInsights (2.9.1) installed, you can follow this doc.

In program.cs:

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

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging=> {
                logging.AddApplicationInsights("your_insturmentation_key");
                logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace); #you can set the logLevel here
            });        
 }

Then in the controller.cs:

    public class HomeController : Controller
    {
        ILogger<HomeController> Logger { get; set; }
        TelemetryClient client = new TelemetryClient();
        public HomeController(ILogger<HomeController> logger)
        {
            this.Logger = logger;
        }

        public IActionResult Index()
        {
            Logger.LogTrace("0225 ILogger: xxxxxxxxxxxxxxxxxxxxxxxxx");
            Logger.LogDebug("0225 ILogger: debug from index page aa111");
            Logger.LogInformation("0225 ILogger: infor from index page aa111");
            Logger.LogWarning("0225 ILogger: warning from index page aa111");
            Logger.Log(LogLevel.Error, "0225 ILogger: error from index page aa111");
            return View();
        }

        # other code

     }

The test result(all logs are sent to application insights):

enter image description here

Share:
16,942
Frédéric Thibault
Author by

Frédéric Thibault

Updated on June 06, 2022

Comments

  • Frédéric Thibault
    Frédéric Thibault almost 2 years

    Using Microsoft.ApplicationInsights.AspNetCore v2.6.1 with .net core v2.2.2 I can see the telemetry going in Azure Application Insight Live Metric Stream but I don't see the entries which I'm trying to log with the ILogger inside the Startup.cs or in a controller.

    I've tried .UseApplicationInsights() with WebHost.CreateDefaultBuilder in Program.cs and also in Startup.cs like so, but to no avail.

    services.AddApplicationInsightsTelemetry( options => {
      options.EnableDebugLogger = true;
    });
    

    I see incoming requests and request failure rate but no log entries with

    this.logger.Log(LogLevel.Error, $"Test Error {Guid.NewGuid().ToString()}");
    this.logger.LogTrace($"Test Trace {Guid.NewGuid().ToString()}");
    this.logger.LogInformation($"Test Information {Guid.NewGuid().ToString()}");
    this.logger.LogWarning($"Test Warning {Guid.NewGuid().ToString()}");
    this.logger.LogCritical($"Test Critical {Guid.NewGuid().ToString()}");
    this.logger.LogError($"Test Error{Guid.NewGuid().ToString()}");
    this.logger.LogDebug($"Test Debug {Guid.NewGuid().ToString()}");