我按照此 link 中的说明在 Azure 中创建了一个 Web 应用程序,并在 .Net core 框架中创建了一个 Web API .
现在,在我的 Web 应用程序中,已启用 Application Insights。
在WebAPI中有一些类似的日志记录代码。
public class Startup
{
public Startup()
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
var logger = loggerFactory.CreateLogger<ConsoleLogger>();
logger.LogInformation("Executing Configure()");
}
}
public class HomeController : Controller
{
ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Executing Home/Index")
return View();
}
}
默认情况下,它会打印一些跟踪日志,类似于 Application Insights 中的类似内容。
2019-01-02T07:22:49 Executing Home/Index
2019-01-02T07:22:49 Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
2019-01-02T07:22:50 Executed action [SomeActionName] (APIName) in 6487.7982ms
2019-01-02T07:22:50 Request finished in 6917.8019ms 200 application/json; charset=utf-8
现在我的要求是它不应该打印 Application Insights 中的所有默认日志。它必须仅打印带有 _logger.LogInformation
的内容。如何以及在哪里禁用此功能?
最佳答案
您可以使用ITelemetryProcessor过滤掉不需要的消息(包括Trace)。
1.您可以使用应用洞察在本地测试您的项目,然后使用应用洞察搜索来检查不需要的跟踪消息,检查其CategoryName(或其他属性)可以指定),如下截图:
2.创建一个实现 ITelemetryProcessor 的自定义类。这里我使用CategoryName来过滤掉不需要的trace消息,你可以自己调整代码:
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
namespace WebApplication1netcore4
{
public class MyTelemetryProcessor : ITelemetryProcessor
{
private ITelemetryProcessor Next { get; set; }
public MyTelemetryProcessor(ITelemetryProcessor next)
{
this.Next = next;
}
public void Process(ITelemetry telemetry)
{
TraceTelemetry trace = telemetry as TraceTelemetry;
if (trace != null && trace.Context.Properties.Keys.Contains("CategoryName"))
{
//Here I just filter out 2 kinds of trace messages, you can adjust your code as per your need.
if (trace.Context.Properties["CategoryName"] == "Microsoft.AspNetCore.Hosting.Internal.WebHost" || trace.Context.Properties["CategoryName"] == "Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker")
{
//return means abandon this trace message which has the specified CategoryName
return;
}
}
if (trace == null)
{
this.Next.Process(telemetry);
}
if (trace != null)
{
this.Next.Process(trace);
}
}
}
}
3.在Startup.cs ->ConfigureServices()方法中,添加以下代码:
services.AddApplicationInsightsTelemetry();
services.AddApplicationInsightsTelemetryProcessor<MyTelemetryProcessor>();
4.经过测试,可以看到不需要的trace消息被过滤掉了。
关于c# - 在应用程序洞察中禁用来自 Web 应用程序的默认跟踪日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54002813/