【问题标题】:NLog GetCurrentClassLogger slow-running method warning: Overstated?NLog GetCurrentClassLogger 运行缓慢的方法警告:夸大了?
【发布时间】:2016-01-31 04:08:39
【问题描述】:

NLog 提到了这个关于“运行缓慢”的评论,我看到其他人重复这个作为警告......好像你在使用 NLog 时应该避免使用GetCurrentClassLogger()

我的问题是:如果您按照建议从静态字段使用 NLog,此警告是否被夸大了?它不是每个类型只运行一次...不是每个new 运行一次吗?

额外的功劳:如果这是真的,为了使这个警告有效,重复初始化一个静态字段需要什么?

/// <summary>
/// Gets the logger with the name of the current class.  
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method. 
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
    return factory.GetLogger(GetClassFullName());
}

【问题讨论】:

    标签: logging nlog


    【解决方案1】:

    NLog 提到了这个关于“运行缓慢”的评论,我看到其他人重复这个作为警告......好像你在使用 NLog 时应该避免使用GetCurrentClassLogger()

    GetCurrentClassLogger 的慢速运行部分是GetClassFullName method,它会扫描StackTrace 以获取当前类名。这不是很慢,但也不是很快,所以在循环中调用GetCurrentClassLogger 重新扫描StackTrace 是一种浪费。需要明确的是,如果 NLog 的性能真的很重要,LogManager.GetLogger("your class name") 总是更快。

    一般来说,在课堂上使用GetCurrentClassLogger 不会影响性能,即使不是static。出于性能原因,建议将其分配给静态字段。

    我的问题是:如果您按照建议从静态字段使用 NLog,此警告是否被夸大了?它不是每个类型只运行一次...不是每个new 运行一次吗?

    TL;DR:是的,您可以在使用 static 字段时忽略此警告。 “慢速部分”确实对每种类型只运行一次。

    额外的功劳:如果这是真的,为了使这个警告有效,重复初始化一个静态字段需要什么?

    只是不要这样做:

    for (int i = 0; i < 100000; i++)
    {
        LogManager.GetCurrentClassLogger().Trace("some cool trace");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2011-05-29
      • 2012-08-16
      相关资源
      最近更新 更多