1

Let's say I have some function that accepts two integers. Is it a way to automatically log a message like this "[Date][MethodNam]([first param],[second param]) - "

What have I tried so far - specify the following layout pattern:

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] [%C.%M] – %message%newline" />
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
seeker
  • 3,255
  • 7
  • 36
  • 68

3 Answers3

2

If you are using an IoC framework such as Windsor you can use AOP (Aspect-oriented programming) to inject a wrapper round your interfaces. You can then log the method call. Here is an example using Windsor and the IInteceptor interface, this is a striped down version of what we use but there are various examples available.

public class LoggingInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Type targetType = invocation.TargetType ?? invocation.Method.DeclaringType;

        ILog logger = LogManager.GetLogger(targetType);

        //Probably want to check logger.IsDebugEnabled

        if(invocation.Arguments.Count() == 0)
        {
            logger.DebugFormat("Method '{0}' called.", invocation.Method);
        }
        else
        {
            var stringBuilder = new StringBuilder("{" + invocation.Arguments.Length + "}");

            for (int i = invocation.Arguments.Length - 1; i > 0; i--)
            {
                stringBuilder.Insert( 0, "{" + i + "}, " );
            }

            logger.DebugFormat("Method '{0}' called with parameters: " + stringBuilder, new[] { invocation.Method }.Union(invocation.Arguments).ToArray());
        }

        try
        {
            invocation.Proceed();

            if (invocation.Method.ReturnType != typeof(void))
            {
                logger.DebugFormat("Method '{0}' returned: {1}", invocation.Method, invocation.ReturnValue);
            }
        }
        catch(Exception ex)
        {
            logger.Error(string.Format("Method '{0}' threw exception:", invocation.Method), ex);
            throw;
        }
    }
}

Depending on your IoC framework you should be able wire up individual components.

POINT TO NOTE:

This will work for interfaces methods only, it will not wire up the private methods on an object.

Bronumski
  • 14,009
  • 6
  • 49
  • 77
0

No idea what is log4net, but you can use reflection to obtain runtime data or debug features and then save it, read more here.

Community
  • 1
  • 1
Sinatr
  • 20,892
  • 15
  • 90
  • 319
0

What you need i called Aspect Oriented Programming (AOP) Here is a list of AOP frameworks. Don't know if any allows you to insert logging of arguments but Loom.net looks promising.

adrianm
  • 14,468
  • 5
  • 55
  • 102