Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

c# - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...