AppInsights 遥测与 SeriLog 日志记录不共存

AppInsights telemetry not co-existing with SeriLog logging

我的Program.cs是这样配置的

            using Infrastructure;
        using Microsoft.AspNetCore.Authentication;
        using Microsoft.AspNetCore.Authentication.AzureAD.UI;
        using Microsoft.AspNetCore.Authentication.JwtBearer;
        using Microsoft.EntityFrameworkCore;
        using Microsoft.Identity.Web;
        using Microsoft.Identity.Web.TokenCacheProviders.InMemory;
        using Serilog;
        using Serilog.Events;
        using Services;
        using Services.Contracts;
        var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        var builder = WebApplication.CreateBuilder(args);

        //builder.Services.AddApplicationInsightsTelemetry(opt => opt.EnableActiveTelemetryConfigurationSetup = true);
        var logger = new LoggerConfiguration()
        // .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        // Filter out ASP.NET Core infrastructre logs that are Information and below
        .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
        .ReadFrom.Configuration(builder.Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();

        try
        {
            // clear all exsiting logging proveriders
            builder.Logging.ClearProviders();
            builder.Logging.AddSerilog(logger);
            builder.Services.AddApplicationInsightsTelemetry();

            var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

            //builder.Services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            //    .AddAzureADBearer(options => configuration.Bind("AzureAd", options));

            builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration, "AzureAd");

            builder.Services.AddCors((options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins, builder => builder
            .WithOrigins("http://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            );
            }));


            var connectionString = configuration.GetConnectionString("BBBankDBConnString");

            // Add services to the container.

            builder.Services.AddControllers();

            builder.Services.AddScoped<ITransactionService, TransactionService>();
            builder.Services.AddScoped<DbContext, BBBankContext>();

            builder.Services.AddDbContext<BBBankContext>(
            b => b.UseSqlServer(connectionString)
            .UseLazyLoadingProxies(true)
            );
            var app = builder.Build();

            // Configure the HTTP request pipeline.
            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
        catch (Exception ex)
        {

            logger.Fatal(ex, "Error Starting BBBank API");
        }
        finally
        {
            logger.Dispose();
        }

设置是这样的

    {
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "BBBankDBConnString": "Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=BBBankDB;Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "bbbankAD.onmicrosoft.com",
    "TenantId": "0c087d99-9bb7-41d4-bd58-80846660b536",
    "ClientId": "api://bbbankapi",
    "Audience": "api://bbbankapi"
  },
  // To configure app insight custom events (custom events for User Specific Actions (User Accessed Accounts Data))
  "ApplicationInsights": {
    "InstrumentationKey": "xxx-ecc6-43d0-9fab-a0d996f4cf07",
    "EnableAdaptiveSampling": false,
    "EnablePerformanceCounterCollectionModule": false
  },
  // To Configure App Insights logging (Applucation Specific Logs e.g Controller Hit)
  "Serilog": {
    "Using": [ "Serilog.Sinks.ApplicationInsights", "Serilog.Sinks.File" ], // "Serilog.Sinks.Debug", "Serilog.Sinks.File",
    "MinimumLevel": "Information",
    // Where do we want to write our logs to? Choose from a large number of sinks:
    // https://github.com/serilog/serilog/wiki/Provided-Sinks.
    "WriteTo": [
      //{
      //  "Name": "Debug"
      //},
      {
        "Name": "File",
        "Args": { "path": "Logs/log.txt" }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "instrumentationKey": "xxx-ecc6-43d0-9fab-a0d996f4cf07",
          //"restrictedToMinimumLevel": "Information",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "Sample"
    }
  }
}

我有这些包裹

  <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="6.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.3">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.3" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.23.1" />
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.20.0" />
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
  <!--<PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
  <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
  <PackageReference Include="Serilog.Sinks.Async" Version="1.4.0" />-->

问题:但遥测工作正常,但日志记录不工作。我也尝试过不同的包组合。还尝试将其中一个注释掉,但结果仍然相同。

    using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;

namespace BBBankAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly TelemetryClient telemetryClient;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, TelemetryClient telemetryClient)
        {
            _logger = logger;
             this.telemetryClient = telemetryClient;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("This is not showing in Azure portal but showing in file");
           telemetryClient.TrackTrace("This is showing in Azure Portal");
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

默认情况下,ApplicationInsights 仅拾取警告或更高版本。您可以将 LogInformation 替换为 LogWarning,或更改配置并查看是否有帮助。 https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#how-do-i- customize-ilogger-logs-collection