使用log4j,如何显示exception的详细内容

本文介绍如何利用Log4j框架记录程序中的异常信息,并通过配置logger.properties文件来指定异常输出的位置及格式。同时,文章提供了示例代码,展示了如何在Java程序中使用Log4j的error方法记录带有堆栈跟踪的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

就像printStackTrace()方法一样。
我在想,Exception还有printStackTrace(PrintStream s)和printStackTrace(PrintWriter s)两个方法,是不是logger有什么组件是可以作为writer来接受输出流的?
请大虾赐教啊!
---------------------------------------------------------------
先下相关的JAR包,设置好CLASSPATH。

import org.apache.log4j.PropertyConfigurator ; 
import org.apache.log4j.Logger ; 
public class A //你的CLASS//
{
  static Logger logger = Logger.getLogger(A.class.getName()); 

  try
{ PropertyConfigurator.configure( "logger.properties" );
//你的代码

}
catch(Exception e)
{logger.info(e);
}
}
在logger.properties中配置相关的文件。
---------------------------------------------------------------
logger的error,warn,debug,info方法均可接收两个参数,Exception要作为第二个参数传入才可打印:

...
catch(Exception e)
{
    logger.error("error", e);
    //or
    //logger.warn("warn", e);
}
...

error方法的说明:
public void error(Object message,
                  Throwable t)
Log a message object with the ERROR level including the stack trace of the Throwable t passed as parameter. 

See error(Object) form for more detailed information.

Parameters:
    message - the message object to log.
    t - the exception to log, including its stack trace.

 

该文章转载自1024k:http://www.1024k.cn/faq/2007/200704/22832.html 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值