【问题标题】:Decentralized NLog Target per Http request每个 Http 请求的去中心化 NLog 目标
【发布时间】:2017-10-23 16:15:32
【问题描述】:

上下文

我正在使用 NLog 和 .NET Web API 2 框架。

服务器是一个多租户环境,其中错误记录到各个客户端数据库。 我有一个 NLog.config 文件,其中包含一个 DatabaseTarget 但缺少(故意)连接字符串属性。 在请求开始时,客户端的连接字符串被获取并以编程方式添加到数据库目标中,以便可以将错误记录到客户端的数据库中。

在执行 Web Api 操作后,我清除了连接字符串,以便后续请求不会登录到错误的数据库。这适用于连续请求。

问题

对服务器的并发请求都试图一次更改数据库目标的连接字符串。这意味着错误将记录到最后一次在数据库目标上设置的数据库。

问题

是否可以将 NLog 实例或至少将日志记录目标隔离到单个请求? 如果没有,我将如何实现这一目标?

注意:需要在 NLog.config 文件中配置数据库目标(连接字符串除外),以便在不更改代码的情况下修改查询。我仍然对不可能的解决方案感兴趣,例如。以编程方式创建数据库目标。

代码

NLog.config 文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <!--
      The logdatabase target's connectionString is
      added programmatically.
    -->
    <target name="logdatabase"
            xsi:type="Database"
            dbProvider="odbc">
      <commandText>
        <!-- super secret query is here -->
      </commandText>
      <!-- super secret parameters are here -->
    </target>
  </targets>

  <rules>
    <!-- rule is added programmatically so that there are no logging attempts before a connection string is added -->
  </rules>
</nlog>

注入连接字符串代码 sn-p(在每个请求开始时调用)

/// <summary>
/// Set up NLog to log to the database.
/// <param name="connectionString">Database to log to</param>
/// </summary>
private void SetUpDatabaseLogging(string connectionString)
{
    DatabaseTarget databaseTarget = LogManager.Configuration.FindTargetByName<DatabaseTarget>("logdatabase");
    databaseTarget.ConnectionString = connectionString;

    // Add rule if it does not exist already
    if (!DatabaseRuleExists("logdatabase"))
    {
        LoggingRule logDatabase = new LoggingRule("*", LogLevel.Debug, databaseTarget);
        LogManager.Configuration.LoggingRules.Add(logDatabase);
    }

    LogManager.ReconfigExistingLoggers();
}

/// <summary>
/// Check if a rule exists that uses the specified target
/// </summary>
/// <returns></returns>
private bool DatabaseRuleExists(string targetName)
{
    bool ruleExists = false;

    foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
    {
        if (rule.Targets.Where(target => target.Name == targetName).Count() > 0)
        {
            ruleExists = true;
            break;
        }
    }

    return ruleExists;
}

删除连接字符串和日志规则的过滤器(在每个控制器上使用)

/// <summary>
/// Clean up log database connection after request
/// </summary>
public class LogCleanUpFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);

        // Remove connection string from logging target.
        DatabaseTarget databaseTarget = LogManager.Configuration.FindTargetByName<DatabaseTarget>("logdatabase");
        databaseTarget.ConnectionString = null;

        // Remove database rule. Rule must not persist between requests
        // because we are logging to client database.
        foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
        {
            if (rule.Targets.Where(target => target.Name == "logdatabase").Count() > 0)
            {
                LogManager.Configuration.LoggingRules.Remove(rule);
                break;
            }
        }

        LogManager.ReconfigExistingLoggers();
    }
}

我正在使用当前类记录器进行记录

private Logger logger = LogManager.GetCurrentClassLogger();
logger.Error("I'm a naughty function");

谢谢各位。对不起,文字墙。

【问题讨论】:

    标签: c# asp.net-web-api2 multi-tenant nlog


    【解决方案1】:

    正如您所注意到的,在多线程环境中全局更改内容很棘手。

    在这种情况下,最好将连接字符串存储在绑定到线程的上下文中。最好的选择是“映射诊断逻辑上下文”(${mdlc}),它绑定到一个线程并且它是异步子线程。

    它还使很多事情变得更容易,因为您不必动态更改规则。

    用法:

    1. 创建一个数据库目标并将 MDLC 用于连接字符串

      在你的 nlog.config 中:

      <target xsi:type="Database"
          name="target1"
          connectionString="${mdlc:myConnectionString}" .. />
      
    2. 在请求的开头设置连接字符串。

      (这就是所有需要的C#)

      MappedDiagnosticsLogicalContext.Set("myConnectionString", "server=...user=..");
      

    就是这样。无需LogManager.ReconfigExistingLoggers,循环/更改 NLog 规则。

    See docs of the MDLC

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 2022-12-19
      • 2021-10-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2021-04-03
      • 2019-02-13
      • 2017-01-06
      相关资源
      最近更新 更多