如何配置log4net以显示调用堆栈和内部异常

时间:2019-05-06 22:32:31

标签: log4net log4net-configuration

我想要的是基本的设置,使日志显示异常的InnerException和每个调用的堆栈。

我的配置是:

{{1}}

但是我得到的是:

  

2019-05-06 16:28:28,042 [1]错误   RunReport.net.windward.samples.RunReport-   RunReportnet.windward.env.DataSourceException:无法加载文件:   c:\ test \ xyz.docx; subtype = INVALID_FILENAME;

上述异常确实具有InnerException(已通过调试器验证)。

我正在使用最新的log4net 2.0.8

1 个答案:

答案 0 :(得分:0)

将以下类添加到您的代码中:

/// <summary>
/// Displays inner exceptions for log4net for Exceptions based on java.lang.Throwable. Needed because
/// System.Exception.ToString() returns the call stacks and inner exceptions. java.lang.Throwable does not.
/// </summary>
public class ThrowablePatternConverter : PatternLayoutConverter
{
    /// <summary>
    /// Write out the info for a logging event. Only writes for a java.lang.Throwable
    /// </summary>
    /// <param name="writer">The log output.</param>
    /// <param name="loggingEvent">The logging event - only if java.lang.Throwable</param>
    protected override void Convert(TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
    {
        Exception ex = loggingEvent.ExceptionObject as java.lang.Throwable;
        if (ex == null)
            return;
        bool first = true;
        while (ex != null)
        {
            if (! first)
                writer.Write($"Caused by: {ex.GetType().FullName}: ");
            first = false;
            writer.WriteLine(ex.Message);

            // call stack
            writer.WriteLine(ex.StackTrace);

            ex = ex.InnerException;
        }
    }
}

并将以下内容添加到您的配置文件中:

                                        <layout type="log4net.Layout.PatternLayout">
                                                        <converter>
                                                                        <name value="throwable" />
                                                                        <type value="Kailua.net.windward.utils.ThrowablePatternConverter" />
                                                        </converter>
                                                        <param name="ConversionPattern" value="%date [%thread] %level %logger - %message%exception%throwable%newline" />
                                        </layout>