Home > Software engineering >  AppInsights telemetry not co-existing with SeriLog logging
AppInsights telemetry not co-existing with SeriLog logging

Time:05-07

my Program.cs is configured like this

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

and the settings are like this

    {
  "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"
    }
  }
}

and the packages i have are these ones

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

Problem: but the telemetry is working but logging is not working . I have tried different combinations of packages as well. Also tried commenting out one over the other but results are stil the same.

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

CodePudding user response:

Only Warning or above is picked up by ApplicationInsights by default. You can replace LogInformation with LogWarning, or change configuration and see if it helps. https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#how-do-i- customize-ilogger-logs-collection

  • Related