log4net的:如何简单的索引(行号)添加到每个日志行行号、索引、简单、日志

2023-09-03 01:44:56 作者:青春很离殇

下面的问题: 我想排索引(行号或迭代器)添加到日志文件中的每一行。 我并不需要它是唯一的整个日志文件,但只适用于应用程序会话(即每次Win32应用程序启动后,我们开始倒计时:1,2,3等)

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)

是任何内置的方式(conversionpattern标记语法),或者一些自定义的扩展?

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

非常感谢!

推荐答案

我的解决方案仅适用于只有一个附加器和计数器复位每次启动应用程序的时间。

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)
    {
        LineCounterPatternConverter.counter++;
        writer.Write(LineCounterPatternConverter.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>

[]括号当然是可选的。你也可以做这样的事情%6LC 这将垫的空间,让你得到的消息对齐很好地行了。

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.