我正在尝试在我的日志文件中打印整个堆栈跟踪。以下是我为各种类编写的示例代码。还给出了日志文件的输出。我希望在日志中打印整个堆栈跟踪。
生成异常的第一个示例DAO:
public String getPasswordByEmail(String email) throws UserException {
try {
beginNewTransaction();
PreparedStatement stmt = getConnection().prepareStatement(GET_PASSWORD_BY_EMAIL);
stmt.setString(1, email);
log.debug("PrepareStatement for selecting user password by email " + stmt.toString());
ResultSet rs = stmt.executeQuery();
if(rs != null) {
rs.next();
}
return rs.getString("password");
}
catch(SQLException sqe) {
throw new UserException("Could not retrieve user details",sqe);
} catch (JiffieTransactionException jte) {
throw new UserException("Error while securing the database connection", jte);
}
}
调用DAO的示例服务类:
public String getPasswordByEmail(String email) throws UserException{
UserDAO userDao = new UserDAO();
return userDao.getPasswordByEmail(email);
}
最终捕获并记录异常的示例动作类:
public String sendPasswordToEmail() {
UserService newService = new UserService();
String password;
try {
password = newService.getPasswordByEmail(email);
} catch (UserException e) {
log.error("Error in RetrievePasswordAction : "+e);
addActionError("Email Id not registered");
return "failure";
} /* more codes */
日志文件的输出:
23 Apr 2015 11:40:44,755 [http-bio-9999-exec-3] ERROR RetrievePasswordAction - Error in RetrievePasswordAction : com.markEffy.aggregator.UserNotFoundException: Email id does not exist
这是我的log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" DLog4jContextSelector="org.apache.logging.log4j.core.async.AsyncLoggerContext Selector">
<Appenders>
<File name="myFile" fileName="${sys:catalina.home}/logs/Aggregator.log">
<PatternLayout pattern= "%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %c{1} %X{user} - %m %n %throwable{full} %n"/>
</File>
</Appenders>
<!-- <Policies>
<SizeBasedTriggeringPolicy size="5 KB"/>
</Policies> -->
<!-- <DefaultRolloverStrategy max="0"/>
</RollingRandomAccessFile>
<Async name="AsyncRollingFile">
<AppenderRef ref="RollingFile"/>
</Async> -->
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n%n"/>
</Console>
<Loggers>
<Logger name="org.apache.log4j.xml" level="debug">
<AppenderRef ref="myFile"/>
</Logger>
<Root level="debug">
<AppenderRef ref="myFile"/>
</Root>
</Loggers>
我希望整个堆栈跟踪进入日志文件。任何帮助都将深受赞赏。
答案 0 :(得分:5)
记录异常以获得完整堆栈跟踪的标准方法是
try {
...
} catch (SomeException ex) {
logger.error("Could not retrieve password", ex); // separate with a comma
}
您的代码段显示log.error("Error in RetrievePasswordAction : "+e)
。问题是您在错误消息和异常对象之间使用了加号。
plus将左侧的字符串连接到右侧的对象,从而生成新的字符串。然后记录这个新字符串。这相当于:
// concatenate String+e.toString() into a new String
String msg = "Error in RetrievePasswordAction : "+e;
log.error(msg); // then log that new string; not what you intended...
答案 1 :(得分:1)
catch (UserException e) {
log.error("Error in RetrievePasswordAction : "+e);
for(int i= 0; i<e.getStackTrace().length; i++){
log.error("+++" +e.getStackTrace()[i] +"+++");
}
我希望这对你有所帮助。不是最好的解决方案,但有效:)