[c#] Log4net rolling daily filename with date in the file name

I would like to have files named for example:

dd.mm.yyyy.log

How is this possible with log4net?

This question is related to c# logging log4net filenames

The answer is


I've tried all the answers, but there was always something missing and not functioning as expected for me.

Then I experimented a bit with the hints given in each answer and was successful with the following setting:

<appender name="RollingActivityLog" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="C:\temp\LOG4NET_Sample_Activity.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <staticLogFileName value="false" />
  <preserveLogFileNameExtension value="true" />
  <datePattern value="-yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level - %message%newline" />
  </layout>
</appender>

The issue with other combinations of parameters was that the latest file didn't have the time pattern, or that the time pattern was appended as .log20171215 which created a new file time (and a new file type!) each day - or both issues appeared.

Now with this setting you are getting files like this one:

LOG4NET_Sample_Activity-20171215.log

which is what I wanted.


To summarize:

  • Don't put the date pattern in the <file value=... attribute, just define it in the datePattern.

  • Make sure you have the preserveLogFileNameExtension value attribute set to true.

  • Make sure you have the staticLogFileName value set to false.

  • Set the rollingStyle attribute value to Date.


For a RollingLogFileAppender you also need these elements and values:

<rollingStyle value="Date" />
<staticLogFileName value="false" />

To preserve file extension:

<log4net>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="D:\\LogFolder\\%date{yyyyMM}\\SchT.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <maximumFileSize value="30MB" />
      <staticLogFileName value="true" />
      <preserveLogFileNameExtension value="true"/>
      <datePattern value="ddMMyyyy" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
  </log4net>

The extended configuration section in a previous response with

 ...
 ...
 <rollingStyle value="Composite" />
 ...
 ...

listed works but I did not have to use

<staticLogFileName value="false" /> 

. I think the RollingAppender must (logically) ignore that setting since by definition the file gets rebuilt each day when the application restarts/reused. Perhaps it does matter for immediate rollover EVERY time the application starts.


Using Log4Net 1.2.13 we use the following configuration settings to allow date time in the file name.

<file type="log4net.Util.PatternString" value="E:/logname-%utcdate{yyyy-MM-dd}.txt" />

Which will provide files in the following convention: logname-2015-04-17.txt

With this it's usually best to have the following to ensure you're holding 1 log per day.

<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />

If size of file is a concern the following allows 500 files of 5MB in size until a new day spawns. CountDirection allows Ascending or Descending numbering of files which are no longer current.

 <maxSizeRollBackups value="500" />
 <maximumFileSize value="5MB" />
 <rollingStyle value="Composite" />
 <datePattern value="yyyyMMdd" />
 <CountDirection value="1"/>
 <staticLogFileName value="true" />

I moved configuration to code to enable easy modification from CI using system variable. I used this code for file name and result is 'Log_03-23-2020.log'

            log4net.Repository.ILoggerRepository repository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            Hierarchy hierarchy = (Hierarchy)repository;
            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date %level - %message%newline%exception";
            patternLayout.ActivateOptions();

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = "Log_";
            roller.DatePattern = "MM-dd-yyyy'.log'";
            roller.Layout = patternLayout;
            roller.MaxFileSize = 1024*1024*10;
            roller.MaxSizeRollBackups = 10;
            roller.StaticLogFileName = false;
            roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
            roller.ActivateOptions();
            hierarchy.Root.AddAppender(roller);


I ended up using (note the '.log' filename and the single quotes around 'myfilename_'):

  <rollingStyle value="Date" />
  <datePattern value="'myfilename_'yyyy-MM-dd"/>
  <preserveLogFileNameExtension value="true" />
  <staticLogFileName value="false" />
  <file type="log4net.Util.PatternString" value="c:\\Logs\\.log" />

This gives me:

myfilename_2015-09-22.log
myfilename_2015-09-23.log
.
.

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  <file value="logs\" />
  <datePattern value="dd.MM.yyyy'.log'" />
  <staticLogFileName value="false" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="5MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to logging

How to redirect docker container logs to a single file? Console logging for react? Hide strange unwanted Xcode logs Where are logs located? Retrieve last 100 lines logs Spring Boot - How to log all requests and responses with exceptions in single place? How do I get logs from all pods of a Kubernetes replication controller? Where is the Docker daemon log? How to log SQL statements in Spring Boot? How to do logging in React Native?

Examples related to log4net

How to use log4net in Asp.net core 2.0 Configure Log4Net in web application log4net hierarchy and logging levels Correct way of using log4net (logger naming) app.config for a class library Log4net does not write the log in the log file Where will log4net create this log file? Configure Log4net to write to multiple files Log4net rolling daily filename with date in the file name log4net vs. Nlog

Examples related to filenames

Rename multiple files in a folder, add a prefix (Windows) How to loop over files in directory and change path and add suffix to filename Why do I get a SyntaxError for a Unicode escape in my file path? Git copy file preserving history A html space is showing as %2520 instead of %20 How do I get the file name from a String containing the Absolute file path? DateTime.ToString() format that can be used in a filename or extension? Get only filename from url in php without any variable values which exist in the url Obtaining only the filename when using OpenFileDialog property "FileName" Build the full path filename in Python