adams85 / filelogger

A lightweight yet feature-rich file logger implementation for the Microsoft.Extensions.Logging framework.
MIT License
147 stars 22 forks source link

Is it possible to implement a log rotate, log.N.txt renames to log.N+1.txt #27

Closed rheatley-pervasid closed 1 year ago

rheatley-pervasid commented 1 year ago

I see issue #2 was closed with, do it externally, but I really need some feature of this library to have

I can almost write this

protected override bool UpdateFilePath(LogFileInfo logFile, FileLogEntry entry, CancellationToken cancellationToken)
{
    var res = base.UpdateFilePath(logFile, entry, cancellationToken);
    if (logFile.Counter == 0)
    {
        return res;
    }

    const int maxFiles = 5;
    logFile.Counter = maxFiles - 1;
    var p = Path.Combine(logFile.BasePath, this.FormatFilePath(logFile, entry));
    File.Delete(p);

    for (int i = maxFiles; i > 1; i--)
    {
        logFile.Counter = i - 1;
        var p1 = Path.Combine(logFile.BasePath, this.FormatFilePath(logFile, entry));

        logFile.Counter = i - 2;
        var p2 = Path.Combine(logFile.BasePath, this.FormatFilePath(logFile, entry));

        try
        {
            File.Move(p2, p1);
        }
        catch (FileNotFoundException)
        {
        }
    }

    logFile.Counter = 0;
    return base.UpdateFilePath(logFile, entry, cancellationToken);
}

But I cannot actually use this with LogFileAccessMode.KeepOpen as the file is in use. logFile.Close() is internal...

Assuming I haven't missed something, is it possible to request something like

adams85 commented 1 year ago

Sure, I'll take a look soon which option is better to enable your use case. Until then, you may use reflection to call the internal method.

adams85 commented 1 year ago

I introduced a new extension point, which makes possible what you want to achieve. I even added a sample app to show the full solution. (If you're ok with hardcoding the file number limit, you may get rid of the extension of options.)

rheatley-pervasid commented 1 year ago

@adams85 that's great. Thank you for a speedy fix :)