如果日志级别低于阈值,则防止昂贵的日志调用 [英] Prevent expensive log call if log level is below threshold

查看:73
本文介绍了如果日志级别低于阈值,则防止昂贵的日志调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行NLog.Trace():

If I do a NLog.Trace():

logger.Trace("Json: {0}", Newtonsoft.Json.JsonConvert.DeserializeObject(myObject));

我的最低级别错误:

<logger name="*" minlevel="Error" writeTo="mail" enabled="false" />

我的对象会被反序列化吗?是的,当然可以.但是我该如何避免呢?

Will my object be deserialized for nothing? Yes, of course yes. But how can I avoid this?

推荐答案

if(logger.IsTraceEnabled)
    logger.Trace("Json: {0}", Newtonsoft.Json.JsonConvert.SerializeObject(myObject));

请参见 IsTraceEnabled .

这是记录呼叫本身的好方法,在这种情况下,呼叫本身可能会很昂贵(如您在上述情况中)或处于重复的高呼叫循环中.对于其他所有内容,通常无需添加检查,因为框架本身在调用中执行相同的检查.

This is good practice for logging calls where the call itself can be expensive (like in your case above) or in a repetitive high call loop. For everything else there usually is no need to add the check as there framework itself performs the same check inside the call.

这篇关于如果日志级别低于阈值,则防止昂贵的日志调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆