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!

1

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.