I am using .net core 2.2 in a sample project and have implemented LoggerFactory and Serilog(for getting logs in .txt file) and they are working fine. But is there a way so that I can turn on logging and off it when I don't need it dynamically without actually doing any code changes and then deploying back into server.
I have made the necessary changes to start the logging functionality and its working pretty good but now I want my system to stop logging errors into the .txt file when I don't want it to log. Means, Is there a way to turn on/off logging functionality.
In Startup.cs, I have added this code to start the .txt logging:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
loggerFactory.AddFile("Logs/log-{Date}.txt");
}
In a controller named customer I have created an instance of the ILogger class.
private ILogger _logger;
public CustomersController(ILogger < CustomersController > logger) {
_logger = logger;
}
And in this TimeTaken function I have used it to log the time taken for the DB call to fetch all customers.
public JsonResult TimeTaken() {
_logger.LogInformation("Controller Called");
Stopwatch sw = new Stopwatch();
sw.Start();
var customers = new List < Customers > ();
if (!_cache.TryGetValue("CustomersList", out customers)) {
if (customers == null) {
customers = _context.Customers.ToList();
}
var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(5));
_cache.Set("CustomersList", customers, cacheEntryOptions);
}
sw.Stop();
var b = sw.ElapsedMilliseconds;
_logger.LogInformation("Data execution took {0} miliseconds", b);
return Json(b);
}
This codes are working fine just want to know if there is a way to turn on/off their functionality on my will. Like calling an api to stop the logging or anything??