nreco / logging

Generic file logger for .NET Core (FileLoggerProvider) with minimal dependencies
MIT License
284 stars 56 forks source link

Multiple file providers with matching prefix #45

Open phoenix172 opened 1 year ago

phoenix172 commented 1 year ago

This had me bashing my head in the wall, until I went to look through the code.

TLDR: If you have multiple file providers and at least one of them is rolling, be sure to use different prefixes for the fileNames or you will get a file in use exception upon opening the rolling file provider. Prefix being the part of the fileName before the first occurrence of a dot .. Example: two providers configured for app.unhandled.log and app.log (rolling) respectively, will cause an error.

I set up two FileLoggerProviders: one for app.unhandled.log and one for a rolling file app.log. I first initialize the app.unhandled.log provider because that is what I am falling back to for unhandled exceptions:

var loggerFactory = LoggerFactory.Create(logging =>
            {
                logging.AddFile("app.unhandled.log");
            });

Later I initialize the app.log provider:

app.ConfigureLogging((context, logging) =>
                {
                    var loggingSection = context.Configuration.GetSection("Logging");
                    logging.AddFile(loggingSection);
                    logging.AddConsole();
                })

Every time I reach logging.AddFile(loggingSection); I was getting a "file is being used exception for app.unhandled.log".

The problem was resolved by changing the name of app.unhandled.log to unhandled.log.

Turns out in FileWriter class, DetermineLastFileLogName method, a pattern is being constructed using the fileName and extension on the passed in log file when using rolling files. The log fileName was app.log in my case. The pattern constructed was app*.log. It then retrieves all log files matching the pattern and starts writing to the one that was last written to, which turns out to be app.unhandled.log. That one is already open for writing though, so we generate a file in use error.

I am not sure of a good way to fix this in the library, but thought it might be good to mention, in case anyone stumbles upon this.

VitaliyMF commented 1 year ago

It makes sense to use even different folders if you use several file logging providers with rolling-files configuration.

Rolling files implementation is definitely not the best, however its logic rather simple. The logic how file prefix is determined can be changed, but this can break backward compatibility, so I guess better do not change it.

phoenix172 commented 1 year ago

In my case, it was a single rolling provider + one more log file, so I don't see the point of adding another folder. Perhaps just an update to the readme, noting the way rolling files are resolved, might be worth it. I don't even consider this a bug per se, just something to be aware of, in order to avoid headaches.