log4net 是否支持在日志消息中包含调用堆栈
我希望在 log4net 消息中包含调用堆栈(例如调用我的方法)。有这样做的标准方法吗?
(我知道这会很慢,但我只需要在出现一些错误时执行此操作)
I wish to include the call stack (e.g. the methods that called me) in a log4net message. Is there a standard way of doing this?
(I know this will be slow, but I only need to do it on some errors)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的 - 您可以在模式布局中使用以下模式获取此堆栈信息:
请参阅 此有关 PatternLayout 的文档了解更多信息。
编辑以下 Ian 的评论:我不认为 log4net 可以配置为写出整个堆栈。
您总是可以使用像 new StackTrace().ToString() 这样的东西自己写出来,但我猜您问的原因是您希望它可以在日志记录中配置配置。
我将进行更深入的研究,但我的直觉是没有办法配置它,并且您最终必须实现自己的布局类。
编辑++
好的 - 这是一个自定义模式布局类,它派生自
PatternLayout
但添加了布局 %stack。这段代码有点粗糙 - 仅用于说明 - 尚未准备好投入生产! (例如,您可能没有安全权限来访问您尝试打印的堆栈)
然后您可以使用以下模式配置进行配置(请注意布局末尾的%stack):
Yes - you can get this stack information using the following patterns in a pattern layout:
See the this documentation on the PatternLayout for more information.
Edit in response to Ian's comment below: I don't think log4net can be configured to write out the whole stack.
You can always fall back on writing it out for yourself, using something like
new StackTrace().ToString()
, but I'm guessing the reason you ask is you want this to be configurable in the logging configuration.I'll have a deeper look, but my gut feeling is there is no way to configure this, and that you'd end up having to implement your own Layout class.
Edit++
OK - here is a custom pattern layout class that derives from
PatternLayout
but adds in a layout %stack.This code is a bit rough - illustrative only - not production ready! (for example, you may not have security permission to access the stack you are trying to print)
You can then configure this with the following pattern configuration (note %stack at the end of the layout):
Robs 的答案是我发现的最好的答案,我决定稍微扩展一下,仅在例外情况下打印完整的堆栈跟踪(如果它对其他人有帮助的话)。
Robs answer was the best i found, i decided to extend it a little to print the full stack trace only for exceptions if it helps anyone else.
如果您捕获异常,则只需记录 Exception.ToString() ,因为它将包含完整的堆栈跟踪,并将作为普通日志消息提供。
If you are catching exceptions, then just log Exception.ToString(), as that will contain the full stack trace, and will be available as the normal log message.
这不是最干净的方法,但实现此目的的一种快速方法是创建一个包含所需堆栈跟踪的人为异常:
(完整源代码)
然后你可以像这样使用它:
It's not the cleanest approach, but a quick way to achieve this is to create an artificial exception that contains the desired stack trace:
(full source)
Then you could use it like so: