【问题标题】:NLog doesn't throw exceptionsNLog 不会抛出异常
【发布时间】:2015-11-09 19:06:10
【问题描述】:

我希望 NLog 在数据库目标连接失败时抛出异常并传递给我的应用程序。

这是我的 NLog 配置文件:

<nlog autoReload="true"
      throwExceptions="true"
      internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log">

现在,当配置文件中有错误时,它会在配置时抛出运行时异常。它还会在内部日志文件中记录有关连接失败的异常,但不会将异常抛回调用应用程序。

我还尝试将 Logger.Log 方法包装在 try-catch 中,以确保它不会吞下它,但 Logger.Log 语句已成功执行。

还有什么可以捕捉应用程序中的异常吗?我只想准备一个未记录的日志事件的缓存,然后在连接再次可用时重新登录到 SQL Server。

编辑:

  1. 我使用的是最新的 NLog 版本 (v4.0)。
  2. 我还确认LogManager.ThrowException 在 运行时。

【问题讨论】:

    标签: c# .net nlog


    【解决方案1】:

    DatabaseTargetWrite 方法包含在 try/catch 中,它只会重新抛出特定类型的异常(StackOverflowThreadAbortOutOfMemoryNLogConfiguration)。如您所述,其他例外情况只会写入内部日志。

    如果您可以选择实现custom target,您可以在其中子类化该方法并覆盖该方法,这将是相当简单的。

     protected override void Write(AsyncLogEventInfo[] logEvents)
     {
        var buckets = SortHelpers.BucketSort(logEvents, c => this.BuildConnectionString(c.LogEvent));
    
        try
        {
            foreach (var kvp in buckets)
            {
                foreach (AsyncLogEventInfo ev in kvp.Value)
                {
                    try
                    {
                        this.WriteEventToDatabase(ev.LogEvent);
                        ev.Continuation(null);
                    }
                    catch (Exception exception)
                    {
                        if (exception.MustBeRethrown())
                        {
                            throw;
                        }
    
                        // in case of exception, close the connection and report it
                        InternalLogger.Error("Error when writing to database {0}", exception);
                        this.CloseConnection();
                        ev.Continuation(exception);
                    }
                }
            }
        }
        finally
        {
            if (!this.KeepConnection)
            {
                this.CloseConnection();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多