Java 用の独自のログハンドラを作成しており、ログ メッセージの行番号を出力に挿入したいと考えています。
これが行番号なしの私の現在の試みです:
public class ConsoleHandler extends Handler {
private static final String SEVERE = "SEVERE";
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Override
public void publish(LogRecord record) {
StringBuilder output = new StringBuilder();
// Add time and location of the message
Date d = new Date(record.getMillis());
String time = new SimpleDateFormat(DATE_TIME_FORMAT).format(d);
output.append(time + ": " + record.getSourceClassName() + "."
+ record.getSourceMethodName() + "\t\t\t");
output.append(record.getLevel() + ": " + record.getMessage());
switch (record.getLevel().getName()) {
case SEVERE:
System.err.println(output);
break;
default:
System.out.println(output);
}
}
public void flush() {}
public void close() throws SecurityException {}
}
LogRecordのインターフェイスを検索しましたが、メッセージがログに記録された行を見つけることができませんでした。
編集: jmehrens の回答にリンクされているコードを適応させました。このメソッドは、行番号とファイル名を取得できるロギング クラスのスタック フレームを返します。
private StackTraceElement getCallerStackFrame(final String callerName) {
StackTraceElement callerFrame = null;
final StackTraceElement stack[] = new Throwable().getStackTrace();
// Search the stack trace to find the calling class
for (int i = 0; i < stack.length; i++) {
final StackTraceElement frame = stack[i];
if (callerName.equals(frame.getClassName())) {
callerFrame = frame;
break;
}
}
return callerFrame;
}
使用法:
final StackTraceElement callerFrame = getCallerStackFrame(record.getSourceClassName());
if (callerFrame != null) {
final String fileName = callerFrame.getFileName();
final int lineNumber = callerFrame.getLineNumber();
// This creates a link to the line when used in Eclipse
output.append("(" + fileName + ":" + lineNumber + ")");
}