Log function calls parameter values & return values in c#

為{幸葍}努か 提交于 2020-01-03 02:47:12

问题


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


来源:https://stackoverflow.com/questions/7393778/log-function-calls-parameter-values-return-values-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!