log4net - conversionPattern per level for single FileAppender?
Asked Answered
E

1

1

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?

Essence answered 4/8, 2015 at 23:40 Comment(0)
H
2

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>
Hartfield answered 20/10, 2015 at 16:3 Comment(1)
Thanks, You explained it quite well. I was struggling to customize the format of %date programmatically. Yours solution helped me in this regards.Airdrop

© 2022 - 2024 — McMap. All rights reserved.