Exceptions for connecting to the async NDS database - how to get them?

Can someone help me in a situation where NLog logs into the database using AsyncTargetWrapperand there is a connection problem? How can I get / catch these exceptions (since asynchronous targets do not throw exceptions)? This seems to be a fairly common scenario, so it's hard for me to believe that this InternalLoggeris the only option. Here's a sample project (NLog nuget package required):

using System;
using System.Threading;
using NLog;
using NLog.Common;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;

class Program
{
    static void Main(string[] args)
    {
        LogManager.ThrowExceptions = true;
        InternalLogger.LogToConsole = true;
        InternalLogger.LogLevel = LogLevel.Error;

        var conf = new LoggingConfiguration();
        var target = new DatabaseTarget
        {
            ConnectionString =
                "Server=BAD_SERVER;Database=foo;",
            CommandText = "INSERT INTO logs(message) VALUES ('bar')"
        };

        var asyncTarget = new AsyncTargetWrapper(target);
        var rule = new LoggingRule("*", LogLevel.Trace, asyncTarget);
        conf.LoggingRules.Add(rule);

        LogManager.Configuration = conf;

        Logger logger = LogManager.GetLogger("Example");
        logger.Info("Message"); // doesn't throw an exception

        Thread.Sleep(16000);

        Console.WriteLine("\nDone");
        Console.ReadLine();
    }
}

Therefore, the application cannot connect to the server (invalid server name in the connection string). After some default (hidden in NLog guts?) Connection time is disabled, the exception is printed to the console using InternalLogger:

2016-01-20 16:39:36.8466 Error Error when writing to database System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

, InternalLogger.LogFile(), -, Azure Web Apps, , ( , , Azure).

NLog?

+4
1

: .

- :

<targets>
  <target xsi:type="FallbackGroup" name="target1" returnToFirstOnSuccess="true">
    <target xsi:type="Database" ... />
    <target xsi:type="File" ... />
  </target>

<targets async="true">, async.

: , , ThrowExceptions =true. , . GitHub.

, , , , MethodCall?

+1

Source: https://habr.com/ru/post/1625150/


All Articles