Log function calls parameter values & return value

2019-05-31 05:53发布

问题:

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:

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



回答2:

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



回答3:

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