log4net - conversionPattern per level for single FileAppender?

放肆的年华 提交于 2019-12-13 01:34:31

问题


While it is not difficult to setup different log files, each with a different conversionPattern, per level, I would like to have minimal logging for all but errors, where I'd like a detailed log entry. Here's a snippet of my current configuration:

<appender name="WarningsAndBelowFileAppender" type="log4net.Appender.FileAppender">
  <file value="log.txt" />
  <appendToFile value="false" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%m%n" />
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMax value="WARN" />
  </filter>
</appender>

<appender name="ErrorsFileAppender" type="log4net.Appender.FileAppender">
  <file value="errors.txt" />
  <appendToFile value="false" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%d [%t] %-5p %c [%x] - %m%n" />
  </layout>
  <threshold value="ERROR" />
</appender>

I'd love to have both of these configurations go into a single log file, just have different conversionPatterns for each. Can this be done?


回答1:


you can't do it within the config file but you can make it with pattern layout converter.

See information here

This should be the converted code:

class MyMessageConverter : PatternLayoutConverter
{
    protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
    {
        if (loggingEvent.Level.Value <= Level.Warn.Value)
        {
            writer.Write(loggingEvent.RenderedMessage);
        }
        else
        {
            writer.Write("{0} [{1}] {2,5} {3} - {4}",
                loggingEvent.TimeStamp,
                loggingEvent.ThreadName,
                loggingEvent.Level.Name,
                loggingEvent.LocationInformation.ClassName,
                loggingEvent.RenderedMessage);

        }
    }
}

And here is the config file:

<appender name="FileAppender" type="log4net.Appender.FileAppender">
  <file value="log.txt" />
  <appendToFile value="false" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%MSG%n" />
      <converter>
        <name value="MSG" />
        <type value="yournamespace.MyMessageConverter " />
      </converter>
  </layout>
</appender>


来源:https://stackoverflow.com/questions/31821137/log4net-conversionpattern-per-level-for-single-fileappender

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!