在方法中缓冲日志

时间:2019-01-29 09:37:31

标签: c# nlog

我有一个WCF服务,我们使用NLog进行日志记录。该服务可以异步调用,因此日志可以异步写入。仅在服务方法完成后,我们才需要将日志缓冲并写入文件中。我该怎么做?

编辑 当前的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="Trace_file"  xsi:type="File" fileName="${basedir}//..//LOGS//Trace//${date:format=dd.MM.yyyy}.log" layout="${longdate}|${uppercase:${level}}|${message}  ${exception:format=tostring,StackTrace}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" maxlevel="Info"  writeTo="Trace_file" />
  </rules>
</nlog>

样品服务

public class Service1 : IService1
    {
        static Logger logger = LogManager.GetCurrentClassLogger();
        public void DoWork(int param)
        {
            logger.Info($"DoWork start ({param})");
            /*
             * Some logic and log write
             */
            logger.Info($"DoWork end ({param})");
        }
    }

异步调用后

2019-02-07 16:53:56.9709|INFO|DoWork start (2002)  
2019-02-07 16:53:56.9709|INFO|DoWork start (2004)  
2019-02-07 16:53:56.9709|INFO|DoWork start (2001)  
2019-02-07 16:53:57.0290|INFO|DoWork end (2002)  
2019-02-07 16:53:57.0370|INFO|DoWork end (2004)  
2019-02-07 16:53:56.9834|INFO|DoWork start (2003)  
2019-02-07 16:53:57.0581|INFO|DoWork end (2003)  
2019-02-07 16:53:57.0761|INFO|DoWork end (2001)  

我需要什么

2019-02-07 16:55:11.0714|INFO|DoWork start (2001)  
2019-02-07 16:55:11.0824|INFO|DoWork end (2001)  
2019-02-07 16:55:11.1150|INFO|DoWork start (2002)  
2019-02-07 16:55:11.1236|INFO|DoWork end (2002)  
2019-02-07 16:55:11.1451|INFO|DoWork start (2003)  
2019-02-07 16:55:11.1541|INFO|DoWork end (2003)  
2019-02-07 16:55:11.1907|INFO|DoWork start (2004)  
2019-02-07 16:55:11.2008|INFO|DoWork end (2004)

0 个答案:

没有答案