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());
}
NLog 提到了这个关于"运行缓慢"的评论,我看到其他人重复这个作为警告......好像在使用 NLog 时应该避免使用
GetCurrentClassLogger()
。
GetCurrentClassLogger
运行缓慢的部分是扫描StackTrace
当前类名的GetClassFullName
方法。这不是很慢,但也不快,所以通过循环调用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");
}