.NET: Logging entry / exit without AOP?

I want to be able to log when code execution enters a method and then exits, I was wondering is anyone has any comments on the best way to achieve this?

I know an AOP way of injecting the logging code at runtime exists but I wanted to have a little more control and PostSharp seems to be a pay framework.

What level of logging would you recommend here, I would think DEBUG.

What about logging timings? How long it takes for the method to enter vs exit

I would love to know what others are doing here and what frameworks you are using.

I am looking at going with log4net.

What i was thinking about logging was the parameters and the name of the method and the values of the parameters, and exiting I was thinking of logging the value of the object that I am returning if returning any at all..

What is everyone else doing?

Thanks in advance


Well, you could certainly create a "disposable logger" that could "automatically" log your information for the methods that you choose:

public class EnterExitLogger : IDisposable
{
  Logger logger;
  string name;

  public EnterExitLogger(Logger logger, string name, params object [] args)
  {
    this.logger = logger;
    this.name = name;
    this.logger.Debug("Entering {0}", this.name);
    int i = 0;
    foreach (var a in args)
    {
      this.logger.Debug("arg[{0}] = {1}", i, a);
      i++;
    }
  }

  public void Dispose()
  {
    this.Logger.Debug("Exiting {0}", this.name);
  }
}

And then use it like this:

public class MyClass
{
  private static readonly Logger logger = LogManager.GetCurrentClassLogger();

  public void SomeMethod(int x, int y)
  {
    using (new EnterExitLogger(logger, "SomeMethod", x, y))
    {
      //Do your work here
    }
  }
}

This doesn't strike me as a particularly good idea, and I doubt that I would do it myself. On the other hand, it does achieve some form of Enter/Exit logging without using AOP. If you really want "automatic" Enter/Exit logging, I'm not sure how to achieve it without AOP or Enterprise Library's version (whose name escapes me).

Obviously there will be some overhead in creating and disposing the EnterExitLogger in my proposed solution, but maybe it is not enough to be a negative for you.


If you don't want to use PostSharp (although there's a free version) or have a runtime proxy generated, there's an open-source alternative for static weaving called Afterthought.

Alternatively, you can use one of the profiling tools. VS Ultimate has one built-in.

链接地址: http://www.djcxy.com/p/95176.html

上一篇: 添加nginx作为ubuntu服务停止并重新加载不起作用

下一篇: .NET:记录没有AOP的入口/出口?