Prevent Serilog from logging home/index request

huangapple go评论61阅读模式
英文:

Prevent Serilog from logging home/index request

问题

在应用程序洞察日志中我看到了许多GET Home/Index请求(每30分钟1500条消息)。我正在寻找一种停止记录这些请求的方法/解决方案。

我在配置中的代码如下:

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

以下是web.cs和appsettings.json文件的内容:

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) => {
                                        //获取配置
                                        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": "*"
}

我正在使用Service Fabric应用程序,并且配置已添加到web.cs文件中。

英文:

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) =&gt; {                                        
var appInsightsOptions = configuration.GetRequiredSection(&quot;AppInsights&quot;).Get&lt;AppInsightsOptions&gt;();
var telemetryConfiguration = new TelemetryConfiguration(appInsightsOptions.InstrumentationKey);
logger                                         
.MinimumLevel.Warning()
.Enrich.FromLogContext()                                        
.Enrich.WithProperty(&quot;ApplicationName&quot;,host.HostingEnvironment.ApplicationName)
.MinimumLevel.Override(&quot;Microsoft&quot;, 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&lt;ServiceInstanceListener&gt; CreateServiceInstanceListeners()
{
return new ServiceInstanceListener[]
{
new ServiceInstanceListener(serviceContext =&gt;
new KestrelCommunicationListener(serviceContext, &quot;ServiceEndpoint&quot;, (url, listener) =&gt;
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $&quot;Starting Kestrel on {url}&quot;);
var currentEnvironment = Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;);
var configuration = new ConfigurationBuilder()
.AddJsonFile(&quot;appsettings.json&quot;, optional: false, reloadOnChange: true)
.AddJsonFile($&quot;appsettings.{currentEnvironment}.json&quot;, optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
return new WebHostBuilder()
.UseKestrel()
.UseConfiguration(configuration)
.ConfigureServices(
services =&gt; services
.AddSingleton&lt;StatelessServiceContext&gt;(serviceContext)
.AddSingleton&lt;ITelemetryInitializer&gt;((serviceProvider) =&gt; FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup&lt;Startup&gt;()
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseUrls(url)
.UseSerilog((host, logger) =&gt; {
//Get Configuration
var appInsightsOptions = configuration.GetRequiredSection(&quot;AppInsights&quot;).Get&lt;AppInsightsOptions&gt;();
var telemetryConfiguration = new TelemetryConfiguration(appInsightsOptions.InstrumentationKey);
logger
.MinimumLevel.Warning()
.Enrich.FromLogContext()
.Enrich.WithProperty(&quot;ApplicationName&quot;,host.HostingEnvironment.ApplicationName)
.MinimumLevel.Override(&quot;Microsoft.AspNetCore&quot;, LogEventLevel.Warning)
.WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Events);
})
.Build();
}))
};
}
}
}
{
&quot;Logging&quot;: {
&quot;LogLevel&quot;: {
&quot;Default&quot;: &quot;Warning&quot;
}
},
&quot;AppInsights&quot;: {
&quot;InstrumentationKey&quot;: &quot;XXXXXXXXXXXXXXXX&quot;
},
&quot;AllowedHosts&quot;: &quot;*&quot;
}

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

答案1

得分: 1

初始输出:

Prevent Serilog from logging home/index request

要防止Serilog记录home/index或任何其他端点请求,请添加以下代码行。

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

我的 Program.cs 文件:

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("从 Program.cs 文件记录日志");
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();

我的 appsettings.json 文件:

{
  "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": "使用Serilog的Application Insights"
  }
}

最终输出(不包括端点 /):

Prevent Serilog from logging home/index request

英文:

Initial Output:

Prevent Serilog from logging home/index request

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

.MinimumLevel.Override(&quot;Microsoft.AspNetCore&quot;, 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(&quot;ApplicationInsights&quot;).GetValue&lt;string&gt;(&quot;ConnectionString&quot;);

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

builder.Logging.AddSerilog(log);

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

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

My appsettings.json file:


{
  &quot;Logging&quot;: {
    &quot;ApplicationInsights&quot;: {
      &quot;LogLevel&quot;: {
        &quot;Default&quot;: &quot;Debug&quot;,
        &quot;Microsoft&quot;: &quot;Error&quot;
      }
    },
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },

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

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

Final Output (without endpoints /):

Prevent Serilog from logging home/index request

huangapple
  • 本文由 发表于 2023年6月26日 22:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定