Log4Net Create a Rolling daily logfile file with Date in the Filename

Today in this article, we shall cover how to create a Log4Net rolling file with a date in the file name.

In our last article, we already learned how to perform file/Rolling File logging in applications using Log4Net in the .NET Core application.

Today in this article, we will cover below aspects,

We leveraged the dependency Injection framework to inject the Log4Net Logger object into the mini IoC DI container in a .NET Core Console application.

Today we will see how to customize the logging file behavior and will see how to add a date in the file.

Please use the below configuration in log4net.config file,

Step1 – Add DatePattern in the log file

<datePattern value="yyyy-MM-dd'.log'"/>

The above “<datePattern../>” tag allows you to use the date pattern in the generated logging file.

Step 2 – Diable StaticLogFileName in the config

This is another step that needs to be done to make date-based log file generation work.

<staticLogFileName value="false"/>

Here is below example of log4net config file,

<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="logs\\TheCodeBuzz-" />
	<datePattern value="yyyy-MM-dd'.log'"/>
    <appendToFile value="true" />
	<staticLogFileName value="false"/>
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="TRACE" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

The generated file will be as below,

below is how i have enabled the lognet logging

See below the implementation for HostBuilder and registration for Log4Net logging.

var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddTransient<MyApplication>();
 
                })
                .ConfigureLogging(logBuilder =>
                {
                    logBuilder.SetMinimumLevel(LogLevel.Trace);
                    logBuilder.AddLog4Net("log4net.config");
 
                }).UseConsoleLifetime();
 
            var host = builder.Build();

For complete step-by-step details please refer below article.

Reference:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *