Write logs to a new log file every time a method is called

Viewed 276

I am using serilog for all my log handling.

I have a method which takes in a filename and processes it inside the method. something like this

ProcessFile(String filename)
{
log.info("started");

log.info("completed");
}

How can I write the logs to a new logfile everytime the method is called to something like {{filename_timestamp}}.log?

Does serilog allow this? Is there a way I can inject the logger into the method directly?

1 Answers

This doesn't seem efficient, but who am I to judge. You could create a new logger each time the method is called, and use it to create the new file each time.

using Serilog;
ProcessFile(string FileName) {
    var logFileName = $"{FileName}_{string.Format("{0:HHmmssfff}", DateTime.Now)}.log" 
    Log.Logger = new LoggerConfiguration()
                      .MinimumLevel.Debug()
                      .WriteTo.Console()
                      .WriteTo.File(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFileName),
                                    rollingInterval: RollingInterval.Infinite,
                                    shared: true)
                      .CreateLogger();
    Log.Information("STARTED - ProcessFile");

    // ProcessFile here

    Log.Information("COMPLETED - ProcessFile");
}

Modify the output path of the file to your needs. The example will place the file at the root of the program.

Related