Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4Net: How to add simple indexer (row number) to each log line

Here is the problem: I want to add row indexer (row number or iterator) to each row in log file. I don't need it to be unique for the whole log file, but only for the "application session" (i. e. each time Win32 application started, we begin our countdown: 1, 2, 3 and so on)

Is where any built-in way (conversionpattern tag syntax) or some custom extension?

Thanks a lot!

like image 885
skaeff Avatar asked Dec 13 '22 19:12

skaeff


1 Answers

My solution only works for one appender only and the counter will be reset every time you start the application.

You could use a pattern converter:

public sealed class LineCounterPatternConverter : PatternLayoutConverter
{       
    private static int _counter = 0;

    protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
    {
        var counter = System.Threading.Interlocked.Increment(ref _counter);
        writer.Write(counter.ToString());
    }
}

then you configure it like this:

<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="[%LC] %message%newline" />
  <converter>
    <name value="LC" />
    <type value="YourNameSpace.LineCounterPatternConverter" />
  </converter>
</layout>

The [] brackets are of course optional. You could also do something like this %6LC which would pad the line with spaces so that you get the message aligned nicely.

like image 52
Stefan Egli Avatar answered Mar 28 '23 01:03

Stefan Egli