0

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)
Alexey
  • 1
  • 1
  • 1
    Can you give us sample code ? – Merhat Pandzharov Jan 29 '19 at 09:38
  • Add a level of indirection, await and log. – InBetween Jan 29 '19 at 09:43
  • 2
    Possible duplicate of this very old question - [Buffering log messages in NLog and manually flushes them to target](https://stackoverflow.com/questions/8153286/buffering-log-messages-in-nlog-and-manually-flushes-them-to-target) – stuartd Jan 29 '19 at 09:44
  • 1
    Possible duplicate of [Buffering log messages in NLog and manually flushes them to target](https://stackoverflow.com/questions/8153286/buffering-log-messages-in-nlog-and-manually-flushes-them-to-target) – Julian Jan 29 '19 at 14:51

0 Answers0