Filtering log4net on method name - can't quite get it

自作多情 提交于 2019-12-05 04:29:59

As far as I can tell log4net does not know a property LocationInfo.MethodName. I am not using Log4PostSharp, so I cannot tell for sure if Log4PostSharp would create this property.

I would write my own filter like this to filter by method names (regex part omitted):

public class MethodNameFilter : StringMatchFilter
{       
     override public FilterDecision Decide(LoggingEvent loggingEvent) 
     {
         if (loggingEvent == null)
         {
              throw new ArgumentNullException("loggingEvent");
         }

         var locationInfo = loggingEvent.LocationInformation;

         // Check if we have been setup to filter
         if (locationInfo == null || (m_stringToMatch == null && m_regexToMatch == null))
         {
             // We cannot filter so allow the filter chain
             // to continue processing
              return FilterDecision.Neutral;
         }

         if (m_stringToMatch != null)
         {
             // Check substring match
             if (locationInfo.MethodName.IndexOf(m_stringToMatch) == -1) 
             {
                  // No match, continue processing
                  return FilterDecision.Neutral;
             }

             // we've got a match
             if (m_acceptOnMatch) 
             {
                  return FilterDecision.Accept;
             } 
             return FilterDecision.Deny;
         }
         return FilterDecision.Neutral;
    }
} 

Note: Accessing LocationInfo is expensive and can have a noticeable effect on performance. You could consider to modify Log4PostSharp to extract the method name during weaving and store it in some property. In that case you could use the property filter as you intended and you would not have any impact on performance. Not sure if this really works but I would expect that this is possible.

The configuration would look something like this:

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
     <filter type="YourNameSpace.MethodNameFilter">
         <stringToMatch value="Page_Load"/>
     </filter>
     <filter type="log4net.Filter.DenyAllFilter" />
     <file value="d:\\xxxx\\yyyyy\\zzzzLog"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!