c# - 如何使 NLog 在运行时线程安全地写入单独的文件目标?

标签 c# multithreading nlog

我有一个运行很多线程(~50)的应用程序,每个线程都从数据库中获取要处理的带锁的付款,然后处理它。
然而,50 个线程使日志不可读、困惑且文件大小巨大。
现在,我想让 NLog 为每个付款 ID 写入一个单独的文件,以便付款处理的所有历史记录都存储在一个文件中。

NLog配置文件:

<?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>
    <target name="file" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
      <target name="f" xsi:type="File" fileName="C:\LogFiles\Immediate\${shortdate}.server.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="file"/>
  </rules>
</nlog>

我现在的代码:

private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); // "2017-07-20.log"

while (!_cancellationToken.IsCancellationRequested)
{
    using (var session = _connectionFactory.GetSession())
    {
        AcquirePaymentWithUpdlockReadpast(session, 
            Logger,  // "2017-07-20.log" 
            payment => {
                if (payment == null)
                    return;

                Logger.Debug($"Payment {payment.Id} has been acquired for processment");

                ProcessPayment(session, Logger, payment); // "2017-07-20.log"
            });
    }

    Thread.Sleep(50);
}

我期望它是什么:

private static readonly ILogger GeneralLogger = LogManager.GetCurrentClassLogger(); // "2017-07-20.General.log"

while (!_cancellationToken.IsCancellationRequested)
{
    using (var session = _connectionFactory.GetSession())
    {
        AcquirePaymentWithUpdlockReadpast(session, 
            GeneralLogger, // "2017-07-20.General.log"
            payment => {
                if (payment == null)
                    return;

                var paymentLogger = LogManager.GetCurrentClassLogger();
                paymentLogger.FileName = $"Payment-{payment.Id}.log"; // <-- I want this. 
                paymentLogger.Debug($"Payment has been acquired for processment");

                ProcessPayment(session, paymentLogger, payment); // "2017-07-20.Payment-123.log"
            });
    }

    Thread.Sleep(50);
}

我找到了一些使用 LogManager.Configuration 的解决方案,但它似乎不是线程安全的。

最佳答案

也许是这样的:

<?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>
    <target name="file" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
      <target name="f" xsi:type="File" fileName="C:\LogFiles\Immediate\${shortdate}.server.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
    </target>
    <target name="paymentFile" xsi:type="AsyncWrapper" queueLimit="10000" overflowAction="Discard">
      <target name="p" xsi:type="File" fileName="C:\LogFiles\Immediate\Payment-${event-properties:PaymentID:whenEmpty=0}.log" layout="${longdate}|${level}|${processid}|${threadid}|${level:upperCase=true}|${callsite:className=false}|${message}" encoding="utf-8"/>
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" writeTo="paymentFile">
         <condition="'${event-properties:PaymentID:whenEmpty=0}'!='0'" action="LogFinal" />
    </logger>
    <logger name="*" minlevel="Debug" writeTo="file"/>
  </rules>
</nlog>

然后你可以像这样进行日志记录(可以使用 NLog-Fluent 进行改进):

LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, $"Payment has been acquired for processment");
theEvent.Properties["PaymentID"] = payment.Id;
Logger.Debug(theEvent);

替代方案可能是这样的:

var paymentLogger = LogManager.GetLogger($"Payment-{payment.Id}");
paymentLogger.Debug($"Payment has been acquired for processment")

然后将 logger-filter 更改为:

<logger name="Payment-*" minlevel="Debug" writeTo="paymentFile" />

然后将 paymentFile 文件名更改为:

fileName="C:\LogFiles\Immediate\{logger}.log" 

关于c# - 如何使 NLog 在运行时线程安全地写入单独的文件目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205121/

相关文章:

.net - 与 Azure Application Insights、ASP.NET MVC 和 NLog 的事件关联

NLog:什么是布局和布局渲染器?

c# - 错误 500 网络 API

Java - 销毁正在做某事的对象

java - 用于在线程中发出信号的信号量不起作用(并发问题)

python - 如何检测线程是否死亡,然后重新启动它?

c# - 如何以编程方式配置 nLog 目标

c# - 使用隐藏窗口在 C# 中打开进程

c# - 如何删除 lambda 事件处理程序

c# - 选择 Word 文档中的目录