Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include header only once at the top of a rolling file

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]&#13;&#10;" />
                <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
like image 256
Noel Avatar asked Jun 26 '12 08:06

Noel


2 Answers

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">
like image 80
user2497188 Avatar answered Sep 22 '22 07:09

user2497188


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.

like image 37
P. Roe Avatar answered Sep 20 '22 07:09

P. Roe