简体   繁体   English

我如何用记录器包装任何方法?

[英]How can i wrap any methods with logger?

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()
}

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.一种可能的方法是使用某种工具重写从您的程序生成的 IL 代码,这样您就可以在编译后注入日志记录。 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.您的“使用”示例可能不是我推荐在公共 API 中使用的示例。但如果您仅在自己的代码中使用它,并且您的同事不抱怨,我真的看不出有任何问题。 Just create something like this class只需创建这样的东西 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM