[英]How to write logs to EventLog by ILogger<T> in Asp.net Core?
[英]How to disable automatic log writing to EventLog at ASP.NET Core 7?
我有一個簡單的 ASP.NET Core 7 Web API 我希望能夠寫入信息 Windows EventLog。
問題是每個對Get()
操作的請求都會自動寫入我想禁用的 EventLog 中的大約 7 個日志,例如:
Request finished HTTP/2 GET https://localhost:44382/weatherforecast - - - 200 - text/plain;+charset=utf-8 2.3546ms
Executed endpoint 'LogTest.Controllers.WeatherForecastController.Get (LogTest)'
Executed action LogTest.Controllers.WeatherForecastController.Get (LogTest) in 0.827ms
我希望能夠將信息日志寫入 EventLog,因此為了禁用 7 個自動日志,我嘗試像這樣過濾 LogLevel
eventLogSettings.Filter = (x, y) => y >= LogLevel.Warning;
但是之后
_logger.LogInformation("My Log Test");
未寫入事件日志。
這是我在Program.cs
中的代碼:
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.LogName = "LogTest";
eventLogSettings.SourceName = "Test1";
eventLogSettings.Filter = (x, y) => y >= LogLevel.Warning;
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
在WeatherForecastController.cs
中:
using Microsoft.AspNetCore.Mvc;
namespace LogTest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
_logger.LogInformation("My Log Test");
return "Test";
}
}
}
在此先感謝您的幫助,
股份公司
您可以嘗試在 appsettings.json 中進行如下設置:
"EventLog": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
}
並查看本文檔中的相關信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.