2

Here is my .net 6 program.cs basic code. In the Following sample code I am trying to write basic logs into Application insights. I have Nuget package reference in my project file

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.21.0" />

I am using classic application insights

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.ApplicationInsights;
using Microsoft.ApplicationInsights.AspNetCore.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services?.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
    ConnectionString = "InstrumentationKey=19233009-a529-494c-9b4b-3fd57d363357;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/;LiveEndpoint=https://centralus.livediagnostics.monitor.azure.com/"

}); 
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();
app.Logger.LogInformation("TEST LOGS");


app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Any suggestions why is it not logging "Test logs" into my application insights logs

Update

As suggested by @jasonc. I followed the instructions from example https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger#example-programcs, and now my logs are getting written from program.cs file to my application insights. But still not logging Ilogger logs from my controller.

I have the following code in my controller, but it is not getting written to application insights.

  public class MyController : Controller
    {
        private readonly ILogger<MyController> _logger;
       

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

       
        public IActionResult Index()
        {
           
           _logger.LogInformation("From myController, running Index.");
         }

   }
roney
  • 964
  • 3
  • 15
  • 37
  • https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger – jasonc Aug 29 '22 at 20:52
  • @jasonc ,Yes I followed the instructions from example https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger#example-programcs, and logs are getting written from program.cs file.But not logging from Ilogger logs from my controller. – roney Aug 30 '22 at 00:40
  • Honestly the code in your controller is good and it is how you would inject your logging. Have you confirmed that your routing is good and your index is being called properly when you run the application? You can always start with something easy writing text to the screen then added your logging above that – jasonc Aug 30 '22 at 14:17

1 Answers1

2

I am able to see the logs in Application Insights with the below changes.

Please Check the below workaround

  • We need to add ApplicationInsights under Logging section in appsettings.json

My appsettings.json

{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    //"InstrmentationKey": "YourInstrumentationKey",
    "ConnectionString": "Your Connection String from Application Insights"
  }
}
  • You can either use InstrumentationKey or ConnectionString.But ConnectionString is recommended.

My Program.cs

using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);

var app = builder.Build();

app.Logger.LogInformation("Configuring for {Environment} environment", app.Environment);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");  
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.Logger.LogInformation("TEST LOGS Final");
app.Logger.LogInformation("From Program, running the host now.");
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

My Controller

 private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            _logger.LogInformation("This is Controller, running Index.");
            return View();
        }

Output

enter image description here

Harshitha
  • 3,784
  • 2
  • 4
  • 9