如何使用 log4net (C#) 记录堆栈跟踪
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9319810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to log stack trace using log4net (C#)
提问by CoolArchTek
How to log stack trace with log4net? I am using .Netversion.
如何记录堆栈跟踪log4net?我正在使用.Net版本。
They way I have is Log.Error(ex).
他们的方式我是Log.Error(ex)。
Thanks
谢谢
回答by James Michael Hare
There are two basic forms, one that takes an object and an exception explicitly:
有两种基本形式,一种明确接受对象和异常:
catch(Exception ex)
{
// the form that takes two args has an exception as second, prints trace...
_log.Error("My custom message", ex);
}
And one that takes any object and performs a ToString()on it:
还有一个接受任何对象并对其执行 a 的方法ToString():
catch(Exception ex)
{
// the form that takes one arg uses ToString()
_log.Error(ex);
}
The former allows you to attach a more meaningful message on the log entry first to give any additional detail you'd like. The latter will do the job but only prints the exception details using ToString(), which gives you:
前者允许您首先在日志条目上附加更有意义的消息,以提供您想要的任何其他详细信息。后者将完成这项工作,但仅使用 打印异常详细信息ToString(),它为您提供:
The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is Nothing, its value is not included in the returned string.
ToString 的默认实现获取抛出当前异常的类的名称、消息、对内部异常调用 ToString 的结果以及调用 Environment.StackTrace 的结果。如果这些成员中的任何一个为 Nothing,则其值不包含在返回的字符串中。
回答by Lloyd
You need to ensure that the definition of the layout pattern is structured to output what format and data you want.
您需要确保布局模式的定义结构化以输出您想要的格式和数据。
Used to output the stack trace of the logging event The stack trace level specifier may be enclosed between braces. For example, %stacktrace{level}.If no stack trace level specifier is given then 1 is assumed
用于输出日志事件的堆栈跟踪堆栈跟踪级别说明符可以用大括号括起来。例如,%stacktrace{level}。如果没有给出堆栈跟踪级别说明符,则假定为 1
Output uses the format: type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1
输出使用格式:type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1
This pattern is not available for Compact Framework assemblies.
此模式不适用于 Compact Framework 程序集。
回答by Maciej
Use this:
用这个:
void Error(object message,Exception t)
Reason is in log4net documentation for void Error(object message):
原因在 log4net 文档中void Error(object message):
WARNING Note that passing an Exception to this method will print the name of the Exception but no stack trace. To print a stack trace use the
void Error(object,Exception)form instead.
警告请注意,将异常传递给此方法将打印异常的名称,但不会打印堆栈跟踪。要打印堆栈跟踪,请改用
void Error(object,Exception)表单。
Error(object message, Exception t)is the most flexible way to log exception data because it goes as an Exception rather than Object and that can be used in appenders to narrow logs to a particular exception class (rather than by searching for a string which is much slower and less consistent)
Error(object message, Exception t)是记录异常数据的最灵活的方式,因为它作为一个 Exception 而不是 Object 并且可以在 appender 中使用以将日志缩小到特定的异常类(而不是通过搜索一个更慢且不太一致的字符串)
There are special versions of all non-format logging methods that take message and exception:
所有非格式日志记录方法都有特殊版本,可以接收消息和异常:
namespace log4net
{
public interface ILog
{
...
/* Log a message object and exception */
void Debug(object message, Exception t);
void Info(object message, Exception t);
void Warn(object message, Exception t);
void Error(object message, Exception t);
void Fatal(object message, Exception t);
...
}
}
回答by Valentin
You can extend the ILog to have a method that logs just an exception with his stack trace.
您可以扩展 ILog 以拥有一个方法,该方法仅通过其堆栈跟踪记录异常。
public static void ErrorWithStackTrace(this ILog log, Exception exception)
{
log.Error(exception.Message,exception);
}
回答by user10767645
public static Logger SetIfNeededAndGetLogger(string serviceName, string methodName)
{
Logger logger = null;
try
{
if (!string.IsNullOrWhiteSpace(serviceName) && !string.IsNullOrWhiteSpace(methodName))
{
ILog log = null;
var traceSourceName = string.Format("{0}{1}", serviceName, methodName);
if (!string.IsNullOrWhiteSpace(traceSourceName))
{
logger = LogSources.FirstOrDefault(x => x.ServiceLogType == traceSourceName);
if (logger == null)
{
log = LogManager.GetLogger(traceSourceName);
//logger = new Logger(log, IHEService.MediLogClientGuid, traceSourceName, methodName);
logger = new Logger(log, System.Guid.NewGuid(), traceSourceName, methodName);
SetLoggingSource(logger);
}
}
}
}
catch (Exception)
{
//silent faiure
}
return logger;
}
private static void SetLoggingSource(Logger value)
{
LogSources.Add(value);
}

