How do I create an asynchronous wrapper for log4net?

后端 未结 6 862
轮回少年
轮回少年 2020-12-13 04:34

By default, log4net is a synchronous logging mechanism, and I was wondering if there was a way to have asynchronous logging with log4net?

6条回答
  •  误落风尘
    2020-12-13 05:02

    Just wanted to provide my complete solution for reference. Couple of important items, the FixFlags let you capture the thread that's actually doing the logging. The Blocking Collection is in the ReactiveExtensions. The jist here is that your forwarding appender handles the Asynchronous stuff and then just forwards on the LoggingEvent to a standard Log4Net appender, which lets Log4Net do all of the things that it's good at. No re-inventing the wheel.

    /// 
    /// Provides an extension for the log4net libraries to provide ansynchronous logging capabilities to the log4net architecture
    /// 
    public class AsyncLogFileAppender : log4net.Appender.ForwardingAppender
    {
        private static int _asyncLogFileAppenderCount = 0;
        private readonly Thread _loggingThread;
        private readonly BlockingCollection _logEvents = new BlockingCollection();
    
        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            loggingEvent.Fix = FixFlags.ThreadName;
            _logEvents.Add(loggingEvent);
        }
    
        public AsyncLogFileAppender()
        {
    
            _loggingThread = new Thread(LogThreadMethod) { IsBackground = true, Name = "AsyncLogFileAppender-" + Interlocked.Increment(ref _asyncLogFileAppenderCount), };
            _loggingThread.Start();
        }
    
        private void LogThreadMethod()
        {
            while (true)
            {
                LoggingEvent le = _logEvents.Take();
                foreach (var appender in Appenders)
                {
                    appender.DoAppend(le);
                }
            }
        }
    }
    

    Then, in your log4net.xml you setup the appenders thusly

    
    
    
    
    
    
        
        
        
        
        
        
        
        
        
        
            
        
    
    

    Update:

    If you want to use context in log4net like "log4net.ThreadContext.Properties["CustomColumn"]"

    Then you need to update above code like

    loggingEvent.Fix = FixFlags.All;
    

提交回复
热议问题