2010-04-14 55 views
7

我使用log4net记录我的web应用程序的进度,使用Log4PostSharp来AOP注入所有方法。这具有记录(几乎)所有内容的理想效果,并且很好。过滤方法名称上的log4net - 不能完全得到它

我现在有要求将Page_Load方法记录到文件/控制台。我显然可以用log4postsharp类来做这件事,但是我会失去所有其他的日志记录。

我一直在寻找log4net中的过滤器,从StringMatch过滤器开始,但只查看正在记录的消息,并且我在方法名称后面。这让我进入了PropertyFilter,但仍然没有快乐。我log4net.config片段是这样的:

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> 
    <filter type="log4net.Filter.PropertyFilter"> 
    <key value="LocationInfo.MethodName"/> 
    <stringToMatch value="Page_Load"/> 
    </filter> 
    <filter type="log4net.Filter.DenyAllFilter" /> 
    <file value="d:\\xxxx\\yyyyy\\zzzzLog"/> 

正如你所看到的,我想Key插入通过LocationInfo记录事件的方法名,但我还是让一切记录下来。编辑:正如在评论中提到的,我现在包括我在RTFM后添加的DenyAllFilter ;-)

任何人都可以协助吗?

谢谢

迈克K.

+0

NB:我现在已经添加了<过滤器类型=“log4net.Filter.DenyAllFilter” />后过滤停止一切被记录,一旦我得到methodname过滤器的工作原理 – 2010-04-14 11:23:27

+0

您是否添加了DenyAllFilter?你会得到一切或没有记录呢?你应该更新你的问题来反映你的进步。 – 2010-04-14 13:01:09

回答

4

至于我可以告诉log4net的不知道财产LocationInfo.MethodName。我没有使用Log4PostSharp,所以我无法确定Log4PostSharp是否会创建此属性。

我会写我自己的过滤器这样的方法名称来过滤(正则表达式部分略):

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; 
    } 
} 

注:访问LocationInfo是昂贵并能对性能有显着的影响。您可以考虑修改Log4PostSharp以在编织过程中提取方法名称并将其存储在某个属性中。在这种情况下,您可以按照您的预期使用属性过滤器,并且不会对性能产生任何影响。不知道这是否真的有效,但我希望这是可能的。

的配置会是这个样子:

<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"/> 
+0

m_stringToMatch在哪里/如何传入? – 2010-05-07 10:06:44

+0

您以与属性过滤器相同的方式配置此新过滤器。你只需要部分。另请参阅我的修订答案。 – 2010-05-07 10:10:13

+0

谢谢 - 有一个赏金;-) – 2010-05-07 10:20:30