Log4j之logger.isInfoEnabled()和logger.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方法。

你可能感兴趣的:(log4j,log,log.info)