1

Say I have a class that looks like this.

public static class Config
{
    public static string GetAppSetting(string key)
    {
        return ConfigurationManager.AppSettings[key].ToString();
    }
}

And I wanted to log every call to this method along with the key parameter & return value.

The only code change I want to make is this:

[Log]
public static class Config
{
    public static string GetAppSetting(string key)
    {
        return ConfigurationManager.AppSettings[key].ToString();
    }
}

I'll most likely use log4net to log the calls from the Log attribute. How can this be achieved?

Thanks in advance!

user896993
  • 1,341
  • 13
  • 15
  • possible duplicate of this one: http://stackoverflow.com/questions/4133569/how-to-log-method-calls-on-targets-marked-with-an-attribute – Davide Piras Sep 12 '11 at 20:46

3 Answers3

3

To my knowledge, the only way you can achieve this is through aspect oriented programming with a library such as PostSharp.

driis
  • 161,458
  • 45
  • 265
  • 341
2

You can use a tool like PostSharp to create a logging aspect.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

The only way this might be possible is to rewrite the generated/compiled IL code for all classes having the [Log] attribute. To do this you need to write a tool that analyzes and manipulates your code and register it as a "Post build event" (in Visual Studio -> Project settings).

For a job like this Mono Cecil might be a great help: http://www.mono-project.com/Cecil

But most propably your better of to rewrite your code and change the method signature to something like

public static string GetAppSetting(string key)
{
    var result = ConfigurationManager.AppSettings[key].ToString();

    Trace.TraceInformation(String.Format("Config.GetAppSetting - Key: {0}, Result: {1}", key, result));

    return result;
}
Peter
  • 3,916
  • 1
  • 22
  • 43