0
votes

I have a batch process that I want to log to MyProcess.YYYYMMDD.log. Usually it runs daily, but sometimes due to failures or testing, it gets run multiple times per day. Based on looking at other log4net questions, I am using the RollingLogFileAppender to create the date-based files. However, if multiple runs happen in the same day, I end up with those multiple runs being logged to the same file.

Ideally, I would like the first run of the batch process to log to MyProcess.YYYYMMDD.log, but the second run in the same day to log to MyProcess.YYYYMMDD.2.log, etc.

What is the easiest way to accomplish this with log4net?

If it is important, my current appender config looks like this:

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="MyProcess.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value=".yyyyMMdd" />
  <staticLogFileName value="false"/>
  <PreserveLogFileNameExtension value="true"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>
2

2 Answers

1
votes

Not sure if you can add an incremented variable to your log's datestamp. Perhaps a better way is to append a timestamp to your file name so that you can differentiate it this way.

This link here gives a good explanation of how to add the neccessary properties to implement a time stamp. If you did not want to log down to the minute you could choose just to use the current hour instead.

1
votes

If you are sure that two processes cannot start at the same time, then you can set your log file programatically.

eg on startup before logging anything set the name of the log file, eg

var logfileName = String.Format("{0}{1:yyyyMMdd}.log" , 
                 ".\logs\MyProcess" , DateTime.Now );

You then check to see if the log file already exists and if so you change the logfileName until you get an unique name.

Then you pass this information to log4net as in.

log4net.GlobalContext.Properties["LogName"] = logfileName;

This needs to be done before the first message is logged.

You also need to change your config file to use this property.

<file type="log4net.Util.PatternString" value="%property{LogName}" />