Log4net: append TimeStamp in the name of a created file

DanCode picture DanCode · Jul 20, 2015 · Viewed 8.4k times · Source

below is the code of my logger config file. When a new txt file is created in my LogFolder, my goal is to append the current timestamp in the name of the file. For example, on July 20th 2015 at 10:27:19am, the file name should be named "logger_2015-07-20_10-27-19.txt"

With the code that I provided, a logger file do get created, but its name is "logger-.txt". The timestamp failed to show up.

Do I need to provide a reference for "${byTimeStamp(local)}? If so, how would I be able to do that?

    <?xml version="1.0" encoding="utf-8"?>
        <configuration>
          <configSections>
            <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
          </configSections>
          <log4net>
            <timestamp key="byTimeStamp" datePattern="yyyy-MM-dd_HH-mm-ss" timeReference="contextBirth"/>
//Here is where I set the name of the logger txt.
            <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
              <param name="File" value="C:\LogFolder\logger_${byTimeStamp(local)}.txt" />
              <param name="AppendToFile" value="true"/>
              <param name="RollingStyle" value="Once"/>
              <param name="DatePattern" value="yyyy-MM-dd'.txt'" />
              <preserveLogFileNameExtension value="true"/>
              <maxSizeRollBackups value="20" />
              <staticLogFileName value="false" />
              <layout type="log4net.Layout.PatternLayout">
                <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
              </layout>
            </appender>
            <root>
              <level value="ALL" />
              <appender-ref ref="LogFileAppender" />
            </root>
          </log4net>
        </configuration>

Answer

Torben Kohlmeier picture Torben Kohlmeier · Aug 19, 2016

Another way to accomplish this:

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString">
        <conversionPattern value="log (%date{yyyy.MM.dd - HH-mm-ss}).log" />
    </file>
    [...]
</appender>