1

I'm using Serilog to log to application insights, but I am only getting the log levels warning, error, and critical to be logged. In appsettings.json, I have the minimum loglevel set to verbose, and this logs everything with the file and console sinks.

By default, application insights can only logs Warning and above. In code (in configure logging), I can add a filter to override this default of warning and above. I preferer to do this in appsettings, with the other logging configuration.

How so I use appsettings to allow Serilog to log all levels to Application Insights?

  • I am getting some logs in application insights so the connectivity is working.
  • I see all loglevels in the logfile and on the console.

Where configuting logging,if I add LogLevel filer (commented out) I can make it work. I needs to work from appsettings.

host.ConfigureLogging(
                loggingBuilder =>
                {
                    var configuration = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json")
                       .Build();
                    var logger = new LoggerConfiguration()
                        .ReadFrom.Configuration(configuration)
                        .CreateLogger();
                    loggingBuilder.AddApplicationInsights();
                    loggingBuilder.AddSerilog(logger, dispose: true);
                    //loggingBuilder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
            
                }
            );

This is my code and the results: enter image description here

Here is my appsettings:

"Serilog": {
    "AllowedHosts": "*",
    "Enrich": [ "WithMachineName" ],
    "MinimumLevel": {
      "Default": "Verbose",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "fileSizeLimitBytes": "1048576",
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact , Version=1.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10",
          "path": "c:\\LogFiles\\Publisher\\Test1\\_log.txt",
          "retainedFileCountLimit": null,
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": "true"
        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "restrictedToMinimumLevel": "Verbose",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ]
  },
Don Chambers
  • 3,798
  • 9
  • 33
  • 74
  • Is there any progress sir? If you feel my post below is helpful to you, could you pls accept it as the answer? – Tiny Wang Jun 07 '21 at 01:28
  • @TinyWang that is what I did, but it's not working. I only see Warning, error, and Critical logged in ApplicaitonSights. I can force it to work but adding this in code: loggingBuilder.AddFilter("", LogLevel.Trace); I need it to work from appsettings. I seem to have the same appsettings as you. – Don Chambers Jun 07 '21 at 13:33
  • I updated the question with code and config examples. Also, I noticed that I do see the Verbose level messages that Microsoft libraries log (in Microsoft.EntityFrameworkCore.Infrastructure), just not when I log them. – Don Chambers Jun 07 '21 at 13:59
  • I think that's because your code covered the appsetting. I remembered that configuration in the code is high level than what in appsetting. I saw that there's no instrumentkey in your appsetting, and could you change your program.cs to what I posted below? In my testing progress, I also find many documents on config serilog but only what I posted below successed. I also can't figure out the reason why only that configuration can work. I think you can also create an empty asp.net core mvc project and copy my code for testing(only replace the instrument key). – Tiny Wang Jun 07 '21 at 14:26
  • There is an instrument key in the appinsights section. The logger gets it, or nothing would be logged (and I can see it in the debugger). – Don Chambers Jun 08 '21 at 02:10
  • I post my local console screenshot below. – Tiny Wang Jun 08 '21 at 02:22

1 Answers1

1

Here's my testing result:

enter image description here

I created my asp.net core mvc application and here's my appsettings.json:

{
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [],
    "MinimumLevel": "Verbose",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "restrictedToMinimumLevel": "Verbose",
          "outputTemplate": "{Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}  {NewLine}{Exception}"

        }
      },
      {
        "Name": "ApplicationInsights",
        "Args": {
          "instrumentationKey": "instrument_key_here",
          "restrictedToMinimumLevel": "Verbose",
          "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId"],
    "Properties": {
      "Application": "Sample"
    }
  }
}

My program.cs, add read configuration code and add UseSerilog():

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace serilog_appsetting_file_appinsights
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .Build();
            Log.Logger = new LoggerConfiguration()
                 .ReadFrom.Configuration(configuration)
                 .CreateLogger();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseSerilog();
    }
}

My packages:

<ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.17.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
  </ItemGroup>

My controller file:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Serilog;
using serilog_appsetting_file_appinsights.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace serilog_appsetting_file_appinsights.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

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

        public IActionResult Index()
        {
            Log.Verbose("serilog_verbose_info");
            Log.Debug("serilog_debug_info");
            Log.Information("serilog_information_info");
            Log.Warning("serilog_warning_info");
            Log.Error("serilog_error_info");
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

When debuging in localhost, we can see app insights capturing logs like this, and see console log

enter image description here enter image description here

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29