log4jで例外のスタックトレースを出力する方法
log4jのスタックトレースの出力方法は次のとおりです。
- org.apache.log4j.Logger
- 申し訳ありませんが、文を日本語に言い換えることはできません。
import org.apache.log4j.Logger;
public class ExampleClass {
private static final Logger logger = Logger.getLogger(ExampleClass.class);
public static void main(String[] args) {
try {
// Some code that may throw an exception
} catch (Exception e) {
logger.error("An error occurred", e);
}
}
}
上の例で、logger.errorメソッドの第一引数はエラーメッセージ、第二引数は例外オブジェクトです。
- org.apache.log4j.ロガー
- この文章をネイティブな日本語に言い換えてください。オプションは1つだけです:エラー
import org.apache.log4j.Logger;
public class ExampleClass {
private static final Logger logger = Logger.getLogger(ExampleClass.class);
public static void main(String[] args) {
try {
// Some code that may throw an exception
} catch (Exception e) {
logger.error("An error occurred", e.toString());
}
}
}
上記例では、e.toString()メソッドによって例外オブジェクトが文字列に変換されます。
どのような方法でも、log4j は例外のスタック情報を自動的に出力して、ログメッセージに含みます。