1

I'm using Application Insights configured for my application. You can refer to this documentationApplicatioInsight

Here is my code:

static TelemetryConfiguration telemetryConfiguration = new TelemetryConfiguration();

public static IHostBuilder UseSerilogCreateHostBuilder(string[] args) =>
     Host.CreateDefaultBuilder(args)
         .ConfigureWebHostDefaults(webBuilder =>
         {
            
              telemetryConfiguration.ConnectionString = configuration["ApplicationInsights:ConnectionString"];                                   
              telemetryConfiguration.SetAzureTokenCredential(new DefaultAzureCredential());
              webBuilder.UseStartup<Startup>();
         })
       .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
             .ReadFrom.Configuration(hostingContext.Configuration)
             .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Traces));

In the Application Insights dashboard, response codes are being logged. The error response codes (500, 401, and 400) and their counts are visible, but no detailed descriptions for these errors are displayed.

Here is the screenshot:

Traces.

Expected failure or transaction log count along with description.

8
  • Click on drill into and check once Commented Oct 8, 2024 at 18:18
  • Are you authenticating your App ? Commented Oct 9, 2024 at 3:57
  • I always search in Transaction search blade instead of Availability blade to get the error/exception details.. Could you pls help check in that menu? Commented Oct 9, 2024 at 6:13
  • It means that SDK successfully submits metrics but not logs/spans. It can be caused by a few (mis)configurations - either on client (app) or ingestion sides. One (preferred) option is to open a support ticket. Another option is to send either instrumentation key or application id to <my SO alias> @ microsoft.com - I can try to look up for something obvious but will not be able to cover everything. Commented Oct 9, 2024 at 7:19
  • 1
    @Harshitha Yes I'm Authenticating my app. Commented Oct 9, 2024 at 10:25

1 Answer 1

0

I created a sample ASP.NET core 8.0 Application and successfully configured authentication, can view traces and their detailed descriptions without any issues.

Make sure you install the latest versions of the below packages.

Serilog
Serilog.Sinks.Console
Serilog.Sinks.ApplicationInsights

My program.cs:

using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Serilog;
using Serilog.Sinks.ApplicationInsights;

var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug().
    .WriteTo.Console() 
    .Enrich.FromLogContext()   .WriteTo.ApplicationInsights(builder.Configuration["ApplicationInsights:ConnectionString"], TelemetryConverter.Traces)
    .CreateLogger();
builder.Host.UseSerilog(); 
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddApplicationInsightsTelemetry();
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{  
    app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/html";
            var exceptionHandlerPathFeature = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerPathFeature>();
            var exception = exceptionHandlerPathFeature?.Error;
       
            Log.Error(exception, "An unhandled exception occurred.");           
            await context.Response.WriteAsync("<h1>Something went wrong.</h1>");
        });
    });
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); 
app.UseAuthorization();  
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});
var logger = Log.ForContext("SourceContext", "Startup");
logger.Information("Application started successfully."); 
app.Run();

appsettings.json:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "MicrosoftFieldLedSandbox.onmicrosoft.com",
    "TenantId": "<Tenant-id>",
    "ClientId": "<client-id>",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "<client-secret>",
    "ClientCertificates": []
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  },
  "DownstreamApi": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": [
      "access_as_user"
    ]
  },
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "ApplicationInsights",
        "Args": { "connectionString": "<connection-string>" }
      }
    ],
    "Enrich": [ "FromLogContext" ]
  },
  "ApplicationInsights": {
    "ConnectionString": "<connection-string>"
  }
}

csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>aspnet-example1insights-<your-ID> </UserSecretsId>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.22.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" NoWarn="NU1605" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.10" NoWarn="NU1605" />
    <PackageReference Include="Microsoft.Identity.Web" Version="2.19.1" />
    <PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="2.19.1" />
    <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.19.1" />
    <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.19.1" />
    <PackageReference Include="Serilog.AspNetCore" Version="8.0.2" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
  </ItemGroup>
</Project>

Successfully authenticated my app

enter image description here

In my App insights I can view the traces and their detailed descriptions.

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.