nreco / logging

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

Specific folder structure #68

Open jecar opened 1 month ago

jecar commented 1 month ago

First of all, thank you for this great logging implementation — simple yet powerful.

I store my log files in a specific folder structure: \ProjectName\[Year]\[Month]\[Day].txt

I have three questions:

 .AddLogging(loggingBuilder =>
 {
     IConfiguration configuration = hostContext.Configuration;

     var loggingSection = configuration.GetSection("Logging");
     loggingBuilder.AddConfiguration(loggingSection);

     loggingBuilder.AddFile(loggingSection.GetSection("File"), fileLoggerOpts =>
     {
         fileLoggerOpts.FormatLogFileName = fName =>
         {
             var nameFormat = string.Format("{0:dd}.txt", DateTime.UtcNow);
             var path = Path.Combine(fName, DateTime.Now.Year.ToString(), DateTime.Now.ToString("MM"));

             if (!Directory.Exists(path))
             {
                 Directory.CreateDirectory(path);
             }

             return Path.Combine(path, nameFormat);
         };

        fileLoggerOpts.FileSizeLimitBytes = 1000000; //10Mo
        fileLoggerOpts.MaxRollingFiles = 10;

         fileLoggerOpts.FormatLogEntry = (msg) =>
         {
             var sb = new System.Text.StringBuilder();
             sb.Append(DateTime.Now.ToString("HH:mm:ss.fff"));
             sb.Append(" ");
             sb.Append(msg.LogLevel.ToString());
             sb.Append(" ");
             sb.Append(msg.Message);
             sb.Append(" ");
             sb.Append(msg.LogName);
             sb.Append(" ");
             sb.Append(msg.EventId.Id);
             sb.Append(" ");
             sb.Append(msg.Exception?.ToString());

             return sb.ToString();
         };
     });
 });
VitaliyMF commented 2 weeks ago

@jecar sorry for the late response.

Is the configuration below the correct way to achieve this?

yes, as this approach is mentioned in README

Will the file/folder rotation occur at midnight as expected when using this in an ASP.NET application?

I guess you're referring to "rolling file" behaviour. It works as long as your "FormatLogFileName" returns the same value. When it returns a new value, this automatically creates a new log file, and if this new path is for another (new and empty) folder everything retated to rolling starts from the beginning.

Will the file rotation upon exceeding the size limit follow the formatting rule and handle the day change correctly, examples :

It's easy to predict rolling files behaviour by realizing that all this logic works only when "FormatLogFileName" returns the same value, and in this case the behaviour is the same as if LogFileName is hardcoded (like 'test.log'). New day leads to a new LogFileName, and everything that was before that doesn't matter for rolling file behaviour.