How to effectively log asynchronously?

前端 未结 10 1068
无人及你
无人及你 2020-12-07 07:28

I am using Enterprise Library 4 on one of my projects for logging (and other purposes). I\'ve noticed that there is some cost to the logging that I am doing that I can miti

10条回答
  •  囚心锁ツ
    2020-12-07 08:04

    In response to Sam Safrons post, I wanted to call flush and make sure everything was really finished writting. In my case, I am writing to a database in the queue thread and all my log events were getting queued up but sometimes the application stopped before everything was finished writing which is not acceptable in my situation. I changed several chunks of your code but the main thing I wanted to share was the flush:

    public static void FlushLogs()
            {   
                bool queueHasValues = true;
                while (queueHasValues)
                {
                    //wait for the current iteration to complete
                    m_waitingThreadEvent.WaitOne();
    
                    lock (m_loggerQueueSync)
                    {
                        queueHasValues = m_loggerQueue.Count > 0;
                    }
                }
    
                //force MEL to flush all its listeners
                foreach (MEL.LogSource logSource in MEL.Logger.Writer.TraceSources.Values)
                {                
                    foreach (TraceListener listener in logSource.Listeners)
                    {
                        listener.Flush();
                    }
                }
            }
    

    I hope that saves someone some frustration. It is especially apparent in parallel processes logging lots of data.

    Thanks for sharing your solution, it set me into a good direction!

    --Johnny S

提交回复
热议问题