C# .NET Core 中的 Azure 应用程序见解

问题描述 投票:0回答:1

我正在使用为我的应用程序配置的 Application Insights。您可以参考这个文档ApplicatioInsight

这是我的代码:

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));

在 Application Insights 仪表板中,正在记录响应代码。错误响应代码(500、401 和 400)及其计数可见,但没有显示这些错误的详细描述。

这是截图:

Traces

预期失败或事务日志计数以及描述。

c# asp.net-core azure-application-insights azureportal
1个回答
0
投票

我创建了一个示例

ASP.NET core 8.0
应用程序并成功配置了身份验证,可以毫无问题地查看跟踪及其详细描述。

确保安装以下软件包的最新版本。

Serilog
Serilog.Sinks.Console
Serilog.Sinks.ApplicationInsights

我的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 文件:

<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>

成功验证我的应用程序

enter image description here

在我的应用程序洞察中,我可以查看痕迹及其详细描述。

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.