Prevent Serilog from logging home/index request

258 Views Asked by At

I see a lot of GET Home/Index requests in the application insight logs (1500 messages in every 30 minutes). I am looking for a way / solution to stop logging these requests.

I have the following code in the code in the configuration.

.UseSerilog((host, logger) => {                                        
  var appInsightsOptions = configuration.GetRequiredSection("AppInsights").Get<AppInsightsOptions>();
  var telemetryConfiguration = new TelemetryConfiguration(appInsightsOptions.InstrumentationKey);
  logger                                         
     .MinimumLevel.Warning()
     .Enrich.FromLogContext()                                        
     .Enrich.WithProperty("ApplicationName",host.HostingEnvironment.ApplicationName)
     .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
     .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Events);
})

Below is the web.cs and appsettings.json file content.

using System.Collections.Generic;
using System.Fabric;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ServiceFabric.Services.Communication.AspNetCore;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using Microsoft.Extensions.Logging;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.ServiceFabric;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Microsoft.Extensions.Configuration;
using System;

namespace projectname
{
    internal sealed class Web : StatelessService
    {
        public Web(StatelessServiceContext context)
            : base(context)
        { }

        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>
                    new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
                         var currentEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

                        var configuration = new ConfigurationBuilder()
                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                           .AddJsonFile($"appsettings.{currentEnvironment}.json", optional: false, reloadOnChange: true)
                           .AddEnvironmentVariables()
                           .Build();

                       return new WebHostBuilder()
                                    .UseKestrel()
                                    .UseConfiguration(configuration)
                                     .ConfigureServices(
                                     services => services
                                    .AddSingleton<StatelessServiceContext>(serviceContext)
                                    .AddSingleton<ITelemetryInitializer>((serviceProvider) => FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .UseStartup<Startup>()
                                    .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                    .UseUrls(url)
                                     .UseSerilog((host, logger) => {
                                        //Get Configuration
                                        var appInsightsOptions = configuration.GetRequiredSection("AppInsights").Get<AppInsightsOptions>();
                                        var telemetryConfiguration = new TelemetryConfiguration(appInsightsOptions.InstrumentationKey);
                                        logger
                                        .MinimumLevel.Warning()
                                        .Enrich.FromLogContext()
                                        .Enrich.WithProperty("ApplicationName",host.HostingEnvironment.ApplicationName)
                                        .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                                        .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Events);
                                    })
                                    .Build();
                    }))
            };
        }
    }
}


    {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "AppInsights": {
    "InstrumentationKey": "XXXXXXXXXXXXXXXX"
  },
  "AllowedHosts": "*"
}

I am using service fabric application and the configuration is added in the web.cs file.

1

There are 1 best solutions below

4
On

Initial Output:

enter image description here

To prevent the Serilog from logging home/index or any other endpoint request, Add the below line of code.

.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)

My Program.cs file:

using Serilog;
using Serilog.Events;
using Serilog.Sinks.ApplicationInsights.TelemetryConverters;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var Conn = builder.Configuration.GetSection("ApplicationInsights").GetValue<string>("ConnectionString");

var log = new LoggerConfiguration()
    .Enrich.FromLogContext()
 .WriteTo.ApplicationInsights(Conn, new TraceTelemetryConverter())
 .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
 .CreateLogger();

builder.Logging.AddSerilog(log);

var app = builder.Build();
app.Logger.LogInformation("Log from Program.cs file");
Log.CloseAndFlush();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");  
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

My appsettings.json file:


{
  "Logging": {
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Debug",
        "Microsoft": "Error"
      }
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=********;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/"
  },

  "WriteTo": [
    {
      "Name": "ApplicationInsights",
      "Args": {
        "restrictedToMinimumLevel": "Information",
        "telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
        "InstrumentationKey": "********"
      }
    }
  ],
  "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
  "Properties": {
    "Application": "Application Insights using Serilog"
  }
}

Final Output (without endpoints /):

enter image description here