How to configure log4net to automatically delete logs?

To automatically delete log files with log4net, you can use the RollingFileAppender and MaxSizeRollBackups properties.

First and foremost, make sure you have properly configured log4net, including using a RollingFileAppender to output logs to a file.

Then, in the RollingFileAppender node of the configuration file, set the MaxSizeRollBackups attribute to a positive integer, indicating the maximum number of log files to retain. For example, setting it to 5 indicates keeping the most recent 5 log files.

The example configuration is as follows:

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="logs/log.txt" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
    </layout>
</appender>

The configuration specified will keep the most recent 5 log files. When the log file reaches the limit of 10MB, log4net will automatically create a new log file and delete the oldest log file.

bannerAds