reflectionlog4netunity-containerunity-interception

How to use Log4Net with interception (MS Unity)


I am try to use Log4Net with Unity and interception... It looks like everything should work , but doesn't... I've two problem... I think with one solution. When I log into the file, I should log also the method that I'm logging. Infact, I have this configuration:

<appender name="MyFileAppender" type="log4net.Appender.RollingFileAppender">
  ...
  <layout type="log4net.Layout.PatternLayout">
    <!-- %d = date, %t = thread, %p = level, %m = message, %n = new line -->
    <param name="ConversionPattern" value="%d{dd/MMM/yyyy HH:mm:ss} [%t] %-2p - %M %m%n"/>
  </layout>
</appender>

In the Pattern I have %M, that should be the method i'm calling... But I am using interception with Unity, so, the logged method name is INVOKE:

var result = getNext().Invoke(input, getNext);

It's this method that call my real method, via reflection. So how can I solve this problem using the PatternLayout of log4Net? Is it possible? And my second problem, I should have two different appenders... I would create a logger with the name MyNamespace.[MyClass].[MyMethod]

<logger name="MyNamespace.MyClass.MyMethod">
  <level value="ERROR" />
  <appender-ref ref="WebsiteFileAppender" />
</logger>

But this can't work, because, for log4net I'm logging another method, that is invoke, instead of my real method. I hope everything is clear.

Can anyone help me please?

Thank you


Solution

  • Just add a custom property to your log4net thread with the name of the method you want to log and log this property in the pattern.

    log4net.ThreadContext.Properties[ "myMethod" ] = theRealMethod;
    

    and in the config

    <conversionPattern value="%logger (%property{myMethod}) [%level]- %message%newline" />
    

    Regarding your second point, log4net doesn't route appenders based on method names but stops at the class name. If you want to log only some events coming from one method just use a LogFilter with a PropertyFilter on the custom property you defined.