打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用Log4j时,为什么要写if (log.isDebugEnabled()) ??

很多东西当真都是要用到的时候,才会拿来仔细研究的。记得当时学的log4j,也就简单了解点,会用他输出下日志好了。搭建日志环境:http://hi.baidu.com/zhangna_307/blog/item/508df78aa02fec719f2fb4f2.html

然后碰到isDebugEnabled方法的时候,就网上好好查了下。

1.看下apache的官方的document,在Performance下那块(From: http://logging.apache.org/log4j/1.2/manual.html)

For example, for some logger cat, writing,

logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));

incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involved.

To avoid the parameter construction cost write:

if(logger.isDebugEnabled() { logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i])); }

This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.

In log4j, logging requests are made to instances of the Logger class. Logger is a class and not an interface. This measurably reduces the cost of method invocation at the cost of some flexibility.

Certain users resort to preprocessing or compile-time techniques to compile out all log statements. This leads to perfect performance efficiency with respect to logging. However, since the resulting application binary does not contain any log statements, logging cannot be turned on for that binary. In my opinion this is a disproportionate price to pay in exchange for a small performance gain.

2.简单来说,就是用isDebugEnabled方法判断下是能提升性能的。(From: http://blog.sina.com.cn/s/blog_616b57310100f36s.html )

 if (logger.isInfoEnabled()) {         logger.info("User " + userId + " is using app " + appId);     }
为什么要加上logger.isInfoEnabled()?原因有两点。

1).直接使用logger.info("User " + userId + " is using app " + appId)来输出log,也能够达到log级别为INFO或在INFO以下时才输出:("User " + userId + " is using app " + appId),因为logger.info方法内部有判断输出级别的代码。但是在进入logger.info函数之前,("User " + userId + " is using app " + appId) 这个表达式已经通过运算拼接成了一个字符串;而如果事先使用 if (logger.isInfoEnabled())进行判断,那么当log级别在INFO以上时,就能省去上述的字符串操作,在高并发和复杂log信息拼接的情况下,使用这种标准的方法输出log能够省去不小的系统开销。另外,如果构造log信息的过程需要大量字符串操作,建议使用StringBuilder来完成字符串拼接。

2).ERROR及其以上级别的log信息是一定会被输出的,所以只有logger.isDebugEnabled和logger.isInfoEnabled方法,而没有logger.isErrorEnabled方法。

 


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Log4j2
Log4net创建日志及简单扩展
Log4j日志级别
if (log.isDebugEnabled()) {}使用场景初析
logback日志,及log4jdbc记录数据库日志 -- 步骤
Log4j的配置
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服