简体   繁体   中英

Is there a to turn on/off the logging functionality in .net core specially the serilog(logging data into .txt file)

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??

Configuration file are used to change application settings without the need to rebuild the application.

Knowing that, here is the most basic way to achieve what you are looking for :

  1. Set up a flag in your appSettings.json
  2. Read the value of the flag from IConfiguration ( see how to do so )
  3. Enable logging depending on the flag value (for instance with a if surrounding loggerFactory.AddFile("Logs/log-{Date}.txt");

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM