Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

logging - When using wrapper, how to preserve class and method name for Log4Net to log?

I need a Log4net wrapper - to be exposed to a number of different components in a large app. I obviously want to retain the class and method name when logging but I would keep away of passing down type etc to my wrapper.

I had a look at this question which is very similar to mine, but it didn't help.

I've seen it done in this other question with smt like the following:

MethodBase methodBase = new StackTrace().GetFrame(1).GetMethod();
this.log.Debug(methodBase.Name + " : " + message);

This is not ideal since it's not using the out-of-the-box Log4Net functionality.

I'd like to get an idea of how people are doing this before I go for the tangent and come up with something very complicated. Any pointers (links/resources/samples) appreciated!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Log4net allows you to access method name for instance like this %method. This is not the fastest operation but if you need to debug something you may very well use it. I believe your question is about the fact that log4net will not output the correct method name if you use a wrapper.

To solve that problem you have to look at how log4net wrote the ILog implementation. This is basically a wrapper around the internal log4net Logger and therefore the very same problem applies to the ILog implementation, too. I did basically the following:

// define a field such as this
private static readonly Type ThisDeclaringType = typeof(MyLogWrapper);

// in constructor. Note: I use the internal Logger!
this.Logger = LogManager.GetLogger(name).Logger;

// I created a WriteLog method that calls the internal logger like this
// you will need to translate to the internal log levels
// message and ex are the items I want to log (ex can be null)
this.Logger.Log(MyLogWrapper.ThisDeclaringType, log4netLevel, message, ex);

Obviously there are some things to do yet, but the important points are mentioned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...