简体   繁体   中英

log4net custom logging

Someone please recommend a better title for this question. I'm not sure what to put.

Right now we have a log wrapper around an instance of ILog that prepends some text to the logged messages. What I'd like to do instead is implement either ILayout or ILogger or IAppender, which could then be specified in our configuration XML. The text I want to prepend isn't static. Because it's used in every log entry, we want to implement it once rather than everywhere we make a log message in the code.

Does this make sense? Which interface should I implement? Right now we use the PatternLayout.

It depends on how you plan to reuse it (for example, when using multiple appenders), but since you are changing the text of the log message, ILayout sounds like the best choice.

You could inherit PatternLayout and do your stuff in Format .

I agree with implementing a custom PatternLayoutConverter. Here a couple of examples:

This one adds the System.Diagnostics.Trace.CorrelationManager.ActivityId to the output:

  public class ActivityIdLayoutConverter : PatternLayoutConverter
  {
    protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent)
    {
      writer.Write(Trace.CorrelationManager.ActivityId.ToString());
    }
  }

This one is parameterized (it can be configured with a key which can be used to retrieve a value from a dictionary - similar to the GDC or MDC):

  class KeyLookupPatternConverter : PatternLayoutConverter
  {
    protected override void Convert(System.IO.TextWriter writer, LoggingEvent loggingEvent)
    {
      string setting;
      //Option is the key name specified in the config file
      if (SomeDictionaryWithYourValues.TryGetValue(Option, out setting))
      {
        writer.Write(setting);
      }
    }
  }

Here is a link to a question that I asked about creating a PatternLayoutConverter that can take a key value. It shows how to do it in log4net and NLog as well as how to configure.

Alternatively, you could wrap a log4net logger and in your wrapper's "Log" method, you could modify the input message or your could put your custom values in the GlobalDiagnosticContext.Properties or ThreadDiagnosticContext.Properties and then reference the values in the output via the normal properties token method.

您可能希望在应用程序上使用依赖项注入,可以在以后将其更改为所需的登录方式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM