简体   繁体   English

log4net和C#扩展方法| 表演

[英]log4net and C# extension method | the performance

I have written an simple extension that should allow me to call method GetLogger in any class. 我写了一个简单的扩展,应该允许我在任何类中调用方法GetLogger。

static class Log4NetExtension {
    public static ILog GetLogger(this object cls) {
        return LogManager.GetLogger(cls.GetType());
    }
}

So, I can log from different class as follows: 因此,我可以从不同的类进行记录,如下所示:

class Test1 {
    public void method() {
        this.GetLogger ().Fatal ("Lorem ipsum no dolor...");
    }
}
class Test2 {
    public void method() {
        this.GetLogger().Error("Lorem ipsum no dolor...");
    }
}

My question is, what exactly LogManager.GetLogger() method call does? 我的问题是,LogManager.GetLogger()方法调用到底是做什么的? Does it creates the logger every time on its method call? 是否在每次调用方法时都创建记录器? Does such approach have a great impact on my application in case I call this.GetLogger() regularly? 如果我定期调用this.GetLogger(),这种方法是否会对我的应用程序产生重大影响?

This is all based off my assumption but to answer this... 这都是基于我的假设,但要回答这个问题...

Does it creates the logger every time on its method call? 是否在每次调用方法时都创建记录器?

This logger most likely follows the singleton pattern which will create an instance of itself if it does not exist. 该记录器很可能遵循单例模式,如果不存在,它将创建其自身的实例。 Then after this, if any new getLogger call is invoked it will return the active instance. 然后在此之后,如果调用任何新的getLogger调用,它将返回活动实例。 The logger is only created one time. 记录器仅创建一次。

Does such approach have a great impact on my application in case I call this.GetLogger() regularly? 如果我定期调用this.GetLogger(),这种方法是否会对我的应用程序产生重大影响?

If the above assumption proves to be true then there should be little to no impact on your program. 如果以上假设被证明是正确的,那么对您的程序几乎没有影响。 Most single threaded loggers usually follow the singleton pattern. 大多数单线程记录器通常遵循单例模式。 If you're working with multiple threads then this gets a little more tricky. 如果您正在使用多个线程,那么这将变得有些棘手。

According to the Log4net documentation the GetLogger() call will look for a logger with that name (the class name you provide) and only create one if it doesn't exist. 根据Log4net文档GetLogger()调用将查找具有该名称(您提供的类名称)的记录器,并且仅在不存在的情况下创建一个。 That's about the best performance you are going to get - lazy create of the logger only if it hasn't already. 那就是您将获得的最佳性能-仅当记录器尚未创建时才懒惰地创建它。

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

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