我需要一个 Log4net 包装器 - 在大型应用程序中暴露给许多不同的组件。我显然想在记录时保留类和方法名称,但我会避免将类型等传递给我的包装器。
我看了this question这与我的非常相似,但没有帮助。
我已经看到它在 this other question 中完成的smt 如下所示:
MethodBase methodBase = new StackTrace().GetFrame(1).GetMethod();
this.log.Debug(methodBase.Name + " : " + message);
这并不理想,因为它没有使用开箱即用的 Log4Net 功能。
在我去切线并提出一些非常复杂的东西之前,我想了解人们是如何做到这一点的。任何指针(链接/资源/示例)表示赞赏!
最佳答案
Log4net 允许您访问方法名称,例如 %method。这不是最快的操作,但如果您需要调试某些东西,您可以很好地使用它。我相信您的问题是关于如果您使用包装器 log4net 将不会输出正确的方法名称这一事实。
要解决该问题,您必须查看 log4net 如何编写 ILog
执行。这基本上是内部 log4net Logger 的包装器,因此同样的问题也适用于 ILog
实现也是如此。我基本上做了以下工作:
// 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);
显然还有一些事情要做,但提到了要点。
关于logging - 使用包装器时,如何为 Log4Net 保留类和方法名称以进行记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2049992/