Home > front end >  How to disable automatic log writing to EventLog at ASP.NET Core 7?
How to disable automatic log writing to EventLog at ASP.NET Core 7?

Time:11-16

I have a simple ASP.NET Core 7 Web API that I would like to be able to write to Information Windows EventLog.

Problem is that each request to Get() action is automatically written to about 7 logs in EventLog that I would like to disable, for example:

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

I would like to be able to write Information log to EventLog so in order to disable the 7 automatic logs I have tried to filter LogLevel like this

eventLogSettings.Filter = (x, y) => y >= LogLevel.Warning;

but then

_logger.LogInformation("My Log Test");

is not written to the EventLog.

Here is my code in 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();

In 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";
        }
    }
}

Thanks in advance for any help,

AG

CodePudding user response:

You may try set as below in appsettings.json:

"EventLog": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning"
      }
    }

And check related information in this document:

  • Related