Linked Questions

Popular Questions

Buffering logs within the method

Asked by At

I have a WCF service and we use NLog for logging. The service can be called asynchronously and therefore logs are written asynchronously. We need the logs to be buffered and written to the file only when the service method has finished. How do I do this?

EDIT Current 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>
    <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>

Sample service

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})");
        }
    }

After async calling

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)  

What i need

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)

Related Questions