【问题标题】:how to log the function calls without calling logger functions inside every function如何在不调用每个函数内的记录器函数的情况下记录函数调用
【发布时间】:2014-07-09 12:45:46
【问题描述】:

我正在将函数调用记录到日志文件中。 我也在使用log4Net

 public Registration Check(Registration registration)
        {

                loggingProvider.Entry();
                //Some code Here
                loggingProvider.Exit();
                return something;
        } 

现在如果我必须输入一个函数调用,我必须在每个函数中手动添加loggingProvider.Entry()

有没有一种方法可以记录在给定命名空间内发生的所有函数调用,并且 LOC 最少?就像在一个地方编写一个函数来记录所有发生的函数调用?

我尝试使用stacktraceget the name of the function being called from the constructor/destructor 并记录它,但这是不可能的。

请提供任何替代方法来获取正在调用的函数名称,而无需在每个函数中手动添加日志函数。

【问题讨论】:

    标签: c# asp.net logging


    【解决方案1】:

    Postsharp 可以帮助解决这个问题。

    http://www.postsharp.net/

    查看http://doc.postsharp.net/method-decorator上方法调用前后的注入行为

    例如,这是取自他们的网站

    [Serializable]
    public sealed class TraceAttribute : OnMethodBoundaryAspect
    {
        // This field is initialized and serialized at build time, then deserialized at runtime.
        private readonly string category;
    
        // These fields are initialized at runtime. They do not need to be serialized.
        [NonSerialized] private string enteringMessage;
        [NonSerialized] private string exitingMessage;
    
        // Default constructor, invoked at build time.
        public TraceAttribute()
        {
        }
    
        // Constructor specifying the tracing category, invoked at build time.
        public TraceAttribute(string category)
        {
            this.category = category;
        }
    
    
        // Invoked only once at runtime from the static constructor of type declaring the target method.
        public override void RuntimeInitialize(MethodBase method)
        {
            string methodName = method.DeclaringType.FullName + method.Name;
            this.enteringMessage = "Entering " + methodName;
            this.exitingMessage = "Exiting " + methodName;
        }
    
        // Invoked at runtime before that target method is invoked.
        public override void OnEntry(MethodExecutionArgs args)
        {
            Trace.WriteLine(this.enteringMessage, this.category);
        }
    
        // Invoked at runtime after the target method is invoked (in a finally block).
        public override void OnExit(MethodExecutionArgs args)
        {
            Trace.WriteLine(this.exitingMessage, this.category);
        }
    }
    

    可以使用[Trace] 修饰需要跟踪的方法(在您的情况下记录),还应该可以创建一个类级别方面,您可以在其中修饰应该与日志记录相关联的类,尽管我自己没有这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多