Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

.net - how to log method name when using wrapper class with Log4net

I am implementing a custom XML formatter for log4.net

public class ISDSApplicationEventsLayout : XmlLayoutBase
{
    protected override void FormatXml(...)
    {
        //Location Info 
        writer.WriteStartElement("Method");
        writer.WriteString(**loggingEvent.LocationInformation.MethodName * *);
        writer.WriteEndElement();
    }
}

The problem is ... now when I call log method from my log wrapper class... called logging

public static void logEvent(string message)
{
    log.Info(isdsLog); 
}

I get the output....

  <Method>logEvent</Method>

How is it possible to have the method name that called logEvent, rather than logEvent as the method name?

Thank you

Question Update:

If this above seems a bit complicated - what I am really asking is : How do you keep the context of the method that called the wrapping logging function in log4net...

example... method doWork()... calls -> logging wrapper --> calls log4net....

How do you make the methodname = doWork and NOT logging wrapper function....

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Actually, you can fix this easily with out-of-the-box log4net. Your wrapper can call Logger.Log and pass the type of your wrapper class as the first parameter. So, your wrapper might look something like this:

public class MyLog4NetWrapper
{
  ILog log = LogManager.GetLogger("WhateverYourLoggerNameIs");

  public void logEvent(string message) 
  {     
    log.Logger.Log(typeof(MyLog4NetWrapper), LogLevel.Info, message, null);
  } 
}

When log4net logs a message, it traverses up the call stack until it gets to the method whose declaring type is equal to the type passed in as the first parameter of the Log method. The next method up the stack is the actual call site.

As far as wrapping the log4net logger, I'm not sure that I would recommend creating a static wrapper class. The main problem with that is that you can only have a single configurable logger in your app.config file. In other words, you won't be able to independently control the logging from different parts of your code. If you have class A and class B and both use your static wrapped logger, then both classes will log at the same level. If you wanted to turn logging on for class A and off for class B, you would not be able to do so.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...