Search code examples
c#log4netlog4net-appenderlog4net-filter

access to filter property from the appender


Given a class extending FilterSkeleton with a property name MyName and an appender extending ApenderSkeleton

is it possible to get the MyName property of the filter which accepted this message while in the Append method of the appender ?

protected override void Append(LoggingEvent loggingEvent)
{
     //sudo
     var somename = acceptedfilter.MyName;

}

Solution

  • You can override the FilterEvent method to save the filter that accepts the message, and then retrieve it in Append:

    public class FilteredAppender : AppenderSkeleton
    {
        private IFilter filter;
    
        protected override bool FilterEvent(LoggingEvent loggingEvent)
        {
            IFilter f = this.FilterHead;
    
            while (f != null)
            {
                if (f.Decide(loggingEvent) == FilterDecision.Accept)
                {
                    filter = f; // Set the filter field
                    break;
                }
    
                f = f.Next;
            }
    
            return base.FilterEvent(loggingEvent);
        }
    
        protected override void Append(LoggingEvent loggingEvent)
        {
            NamedFilter acceptedfilter = filter as NamedFilter;            
    
            if (acceptedfilter!= null)
            {
                  var somename = acceptedfilter.MyName;
                  // etc
            }
        }
    }