Include a title only once at the top of the sliding file

Is it possible to include only the header information at the top of the sliding file?

I have the following configuration 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 the header information twice, for example.

  [Header] The Log line [Header] The Log line etc 

I want to achieve the following results:

  [Header] The Log line The Log line etc 
+7
source share
3 answers

The easiest way I found for this is to create a class that inherits from RollingFileAppender and overwrite this 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() { if (LockingModel.AcquireLock().Length == 0) { base.WriteHeader(); } } } } 

then use this class as appender:

 <appender name="CsvFileAppender" type="CsvLogging.HeaderOnceAppender"> 
+10
source

Create a specific implementation of log4net.Layout.PatternLayout:

 namespace MyApplication { using log4net.Layout; public class MyConcretePatternLayout : PatternLayout { public override string Header => "My Header text here" } } 

Modify the log4net.config file to use this new template:

  <appender name="MyFileAppender" type="log4net.Appender.RollingFileAppender"> ... <layout type="MyApplication.MyConcretePatternLayout"> <conversionPattern... </layout> </appender> 

Now that the file is being downloaded due to your criteria, you should see β€œMy title is text here” at the top of each file.

+3
source

You need a custom appender that inherits from RollingFileAppender. See the message below.

Log4net - how to find out when a file is scanned?

Basically, you need to provide your own logic in the user application in order to write your own header for each new file. You will probably do this in RollOverSize. It would be nice to get a copy of the log4net source code for reference.

0
source

All Articles