Home > Back-end >  How can i wrap any methods with logger?
How can i wrap any methods with logger?

Time:01-28

There is a sample method call via service instance.

 _logger.LogDebug("Create runned !");
 await _service.Create();
_logger.LogDebug("Create completed successfully");

How can i write log before enter and after called method more efficient ?

For example:

using(Log.Wrapper())
{
   await _service.Create()
}

CodePudding user response:

One possible approach is to use some tool to rewrite the produced IL-code from your program, that way you can inject logging post compilation. This article seem to describe the practice, and I have seen commercial tools, but it is not something I have used.

The approach I tend to use is to create a decorator, often using a helper method do the actual logging from a central place:

public class MyLoggingDecorator : IMyInterface{

public MyLoggingDecorator(IMyInterface backing, ILogger logger){...}

private T LogBeforeAndAfter(Func<T> method, [CallerMemberName]string caller = null){
    logger.Info("Called: "   caller);
    var result = method();
    logger.Info("Call "   caller   " completed");
    return result;
}
int IMyInterface.MyExampleMethod(int parameter) => LogBeforeAndAfter(() => backing.MyExampleMethod(parameter));

This has some overhead, and is not as efficient as just calling the log directly in each method, but it can help to make the code more compact. And any overhead is probably less then the cost to do the logging in the first place.

Your 'using'-example is probably not something I would recommend using in a public API. But if you only use it in your own code, and your colleagues don't complain, I do not really see any problem with it. Just create something like this class

public class LogBeforeAndAfter : IDisposable
{
    private readonly ILogger log;
    private readonly string caller;

    public LogBeforeAndAfter(ILogger log, string caller)
    {
        this.log = log;
        this.caller = caller;
        log.Info("Called: "   caller);
    }

    public void Dispose() => log.Info("Call "   caller   " completed");
}
...
public static LogBeforeAndAfter LogBeforeAndAfter(this ILogger log, [CallerMemberName] string caller = "") => new (log, caller);

  • Related