Is it possible to only include header information at the top of a rolling file?
I have the following config file:
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="d:\temp\TTTest.log"/>
<layout type="log4net.Layout.PatternLayout">
<header value="[Header] " />
<param name="ConversionPattern" value="%-25utcdate{dd/MM/yyyy HH:mm:ss.fff}%-20property{log4net:HostName}%-30logger%-30thread%-7level%message%newline"/>
</layout>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<maximumFileSize value="5MB"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="-1"/>
<countDirection value="1"/>
</appender>
When I run my application, for example twice I get header information twice e.g.
[Header]
The Log line
[Header]
The Log line
etc
I am looking to achieve the following:
[Header]
The Log line
The Log line
etc
The easiest way I've found to do this is to create a class that inherits from RollingFileAppender and overwrites like this the WriteHeader method :
using System.IO;
using System.Text;
using log4net.Core;
using log4net.Layout;
using log4net.Util;
using log4net.Appender;
namespace CsvLogging
{
public class HeaderOnceAppender : RollingFileAppender
{
protected override void WriteHeader()
{
try
{
if (LockingModel.AcquireLock().Length == 0)
{
base.WriteHeader();
}
}
finally
{
LockingModel.ReleaseLock();
}
}
}
}
then use this class as appender :
<appender name="CsvFileAppender" type="CsvLogging.HeaderOnceAppender">
Create a concrete implementation of the log4net.Layout.PatternLayout :
namespace MyApplication
{
using log4net.Layout;
public class MyConcretePatternLayout : PatternLayout
{
public override string Header => "My Header text here"
}
}
Modify your log4net.config file to use this new custom pattern layout :
<appender name="MyFileAppender" type="log4net.Appender.RollingFileAppender">
...
<layout type="MyApplication.MyConcretePatternLayout">
<conversionPattern...
</layout>
</appender>
Now whenever the file rolls due to your criteria you should see "My Header text here" at the top of each file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With