开发者

Log function calls parameter values & return values in c#

开发者 https://www.devze.com 2023-04-04 04:10 出处:网络
Say I have a class that looks like this. public static class Config { public static string GetAppSetting(string key)

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 st开发者_如何学Goring 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!


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消