前几天同事突然问了个问题让我不大理解,先在这里记录下。
1.log4j.error和e.printstacktrace()有什么区别?
我的理解当然很简单,e.printstacktrace()是在控制台输出来的,logger4j是在日志中输出来的。
后来同事打了个哑谜还有一个是关系到buffer上的区别,对于这点其实我还是没有怎么搞明白,有知道的小伙伴可以来解答下。
2.logger.error(exception)和logger.error("",exception) 看很多人都是后者的写法,为什么就不能直接用logger.error(exception)呢?
对于这个问题我们可以对比下输出结果就知道了,发现前者只打印一行报错信息,后者却可以打印出堆栈信息。其实这个问题可以在源码中探索出来。原来前者只把excetion.toString()当成message,异常信息设置成null了。
/**
Log a message object with the {@link Level#ERROR ERROR} Level.
This method first checks if this category is ERROR
enabled by comparing the level of this category with {@link
Level#ERROR ERROR} Level. If this category is ERROR
enabled, then it converts the message object passed as parameter
to a string by invoking the appropriate {@link
org.apache.log4j.or.ObjectRenderer}. It proceeds to call all the
registered appenders in this category and also higher in the
hierarchy depending on the value of the additivity flag.
WARNING Note that passing a {@link Throwable} to this
method will print the name of the Throwable but no
stack trace. To print a stack trace use the {@link #error(Object,
Throwable)} form instead.
@param message the message object to log */
public
void error(Object message) {
if(repository.isDisabled(Level.ERROR_INT))
return;
if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.ERROR, message, null);
}
/**
Log a message object with the ERROR level including
the stack trace of the {@link Throwable} t passed as
parameter.
See {@link #error(Object)} form for more detailed information.
@param message the message object to log.
@param t the exception to log, including its stack trace. */
public
void error(Object message, Throwable t) {
if(repository.isDisabled(Level.ERROR_INT))
return;
if(Level.ERROR.isGreaterOrEqual(this.getEffectiveLevel()))
forcedLog(FQCN, Level.ERROR, message, t);
}
具体的demo代码如下:
package tools;
import org.apache.log4j.Logger;
import entity.User;
public class Log4jTest {
private static Logger logger=Logger.getLogger(Log4jTest.class);
/**
* @param args
*/
public static void main(String[] args) {
try
{
User user = null;
Integer.parseInt(user.getContent_append());
}catch(Exception ex)
{
//logger.debug("debug");
logger.error("",ex);
}
}
}