我正在为 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 + ")");
}