NLog 不会抛出异常
NLog doesn't throw exceptions
我希望 NLog 在数据库目标连接失败时抛出异常并传递给我的应用程序。
这是我的 NLog 配置文件:
<nlog autoReload="true"
throwExceptions="true"
internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log">
现在,当配置文件中存在错误时,它会在配置时抛出 运行time 异常。它还会在内部日志文件中记录有关连接失败的异常,但不会将异常返回给调用应用程序。
我还尝试将 Logger.Log 方法包装在 try-catch
中以确保它不会吞下它,但 Logger.Log 语句已成功执行。
还有什么可以捕获应用程序中的异常吗?我只想准备一个未记录的日志事件的缓存,然后在连接再次可用时重新登录到 SQL 服务器。
编辑:
- 我使用的是最新的 NLog 版本 (v4.0)。
- 我也确认
LogManager.ThrowException
是真的
运行-时间也是。
DatabaseTarget
的 Write
方法被包装在 try/catch 中,它只会重新抛出特定类型的异常(Whosebug
、ThreadAbort
、 OutOfMemory
,和 NLogConfiguration
)。正如您所注意到的,其他异常只会写入内部日志。
实现一个 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();
}
}
}
我希望 NLog 在数据库目标连接失败时抛出异常并传递给我的应用程序。
这是我的 NLog 配置文件:
<nlog autoReload="true"
throwExceptions="true"
internalLogLevel="Debug" internalLogFile="c:\temp\nlog-internal.log">
现在,当配置文件中存在错误时,它会在配置时抛出 运行time 异常。它还会在内部日志文件中记录有关连接失败的异常,但不会将异常返回给调用应用程序。
我还尝试将 Logger.Log 方法包装在 try-catch
中以确保它不会吞下它,但 Logger.Log 语句已成功执行。
还有什么可以捕获应用程序中的异常吗?我只想准备一个未记录的日志事件的缓存,然后在连接再次可用时重新登录到 SQL 服务器。
编辑:
- 我使用的是最新的 NLog 版本 (v4.0)。
- 我也确认
LogManager.ThrowException
是真的 运行-时间也是。
DatabaseTarget
的 Write
方法被包装在 try/catch 中,它只会重新抛出特定类型的异常(Whosebug
、ThreadAbort
、 OutOfMemory
,和 NLogConfiguration
)。正如您所注意到的,其他异常只会写入内部日志。
实现一个 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();
}
}
}