How do I force a rollover at application startup with Log4net RolloverFileAppender?

StackOverflow https://stackoverflow.com/questions/222210

  •  03-07-2019
  •  | 
  •  

Question

Have Log4Net configured in our application to use a date stamped name and a 10Meg file size limit.
This automatically causes a rollover to a new file at midnight and whenever the 10Meg limit is reached. I would also like to roll over the logging to a new file each time the application is started (or closed).
Can I get all three roll over behaviours?

Was it helpful?

Solution

Set appendToFile to false in your config file.

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
....
  <appendToFile value="false" />
....
</appender>

EDIT: To answer Craig's comment:

If you properly setup StaticLogFileName and CountDirection (see http://logging.apache.org/log4net/release/sdk/log4net.Appender.RollingFileAppender.html for more), then things roll as desired. We programmatically configure the logger in our app where we use this, but this is what the code looks like:

Dim Layout As New PatternLayout("%date{yyyy-MM-dd HH:mm:ss,fff} [%-6thread] %-5level %type{2}.%method(%line) - %message%newline") 
Dim Appender As New log4net.Appender.RollingFileAppender()
Appender.File = Path.Combine(FileSystemHelper.LogDirectory, LogFileName)
Appender.Layout = Layout
Appender.AppendToFile = False ' we will start a new one when the program starts'
Appender.Name = "RollingLogFileAppender"
Appender.Threshold = LogLevel() 'May want to set this by configuration'
Appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size 'This means it will start a new log file each time the log grows to 10Mb'
Appender.MaximumFileSize = "10MB"
Appender.MaxSizeRollBackups = -1 'keep an infinite number of logs'
Appender.StaticLogFileName = True
Appender.CountDirection = 1 ' to reduce rollover costs'
log4net.Config.BasicConfigurator.Configure(Appender)
Appender.ActivateOptions()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top