Как я могу использовать NLog для входа в конкретную базу данных в API?

В нашей организации каждый клиент имеет свою собственную базу данных с соответствующей таблицей регистрации. Как я могу сконфигурировать NLog программно, чтобы я мог указать правильную базу данных для каждого клиента?

Что-то вроде:

var loggerA = LogManager.GetLogger("CustomerA");
loggerA.Log("Customer A Record");
//Outputs to DatabaseA

LogManager.GetLogger("CustomerB");
loggerB.Log("Customer B Record");
//Outputs to DatabaseB

Кроме того, мы пытаемся настроить это с помощью Common.Logging, если это актуально.

В настоящее время у нас есть следующее, что мы собираемся адаптировать:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog.Config;
using NLog;
using NLog.Targets;

namespace Internal.Logging
{
    public static class LoggingManager
    {
        public static void ConfigureLogging(string databaseTargetConnectionString = null)
        {
            ConfigureCommonLogging();
            ConfigureAdapter(databaseTargetConnectionString);
        }

        private static void ConfigureAdapter(string databaseTargetConnectionString)
        {
            // Step 1. Create configuration object 
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var debuggerTarget = new DebuggerTarget();
            config.AddTarget("console", debuggerTarget);
            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            if (!string.IsNullOrEmpty(databaseTargetConnectionString))
            {
                var databaseTarget = new DatabaseTarget();
                databaseTarget.ConnectionString = databaseTargetConnectionString;
                config.AddTarget("database", databaseTarget);
            }

            // Step 3. Set target properties 
            debuggerTarget.Layout = @"${date:format=HH\\:MM\\:ss} ${message}";
            fileTarget.FileName = "${basedir}/file.txt";
            fileTarget.Layout = "${message}";

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", LogLevel.Debug, debuggerTarget);
            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }

        private static void ConfigureCommonLogging()
        {
            var properties = new Common.Logging.Configuration.NameValueCollection();
            properties.Add("configType", "INLINE");
            Common.Logging.LogManager.Adapter = new Common.Logging.NLog.NLogLoggerFactoryAdapter(properties);
        }
    }
}

1 ответ

Что-то вроде того:

<?xml version="1.0" ?>
<nlog autoReload="true">
    <targets>
        <target name="databaseA" type="Database">
            <dbprovider>mssql</dbprovider>
            <!-- params -->
        </target>
        <target name="databaseB" type="Database">
            <dbprovider>mssql</dbprovider>
            <!-- params -->
        </target>       
    </targets>

    <rules>
        <logger name="CustomerA" minlevel="Debug" appendTo="databaseA" />
        <logger name="CustomerB" minlevel="Debug" appendTo="databaseB" />       
    </rules>
</nlog>
Другие вопросы по тегам