你可以創建你自己的java.util.logging.Formatter
。爲此,你可以這樣擴展它:
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public final class MyFormatter extends Formatter {
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
// Build output the way you want
sb.append(new Date(record.getMillis()))
.append(" \t")
.append(record.getThreadID())
.append(" \t")
.append(record.getSourceMethodName())
.append(" \t")
.append(record.getSourceClassName())
.append(" \t")
.append(record.getLevel().getLocalizedName())
.append(": ")
.append(formatMessage(record))
.append(System.getProperty("line.separator"));
return sb.toString();
}
}
你明白了。
這只是您如何處理輸出並使用\ t對齊它的示例。這不是一個完美的解決方案,因爲您事先不知道SourceMethodName或SourceClassName或任何其他輸出字段的長度,只有一個\ t可能不足以完全對齊它們。
該解決方案可能會盡可能多地被使用以覆蓋幾乎所有您可以想到的情況。
也就是說,完美的解決方案是保存所有輸出信息,最後根據每個字段的長度計算使用多少個\ t。
編輯:
代替\ t您可以String.format()
一起使用StringBuilder
一個更清潔,更易於閱讀代碼:
sb.append(String.Format("[%1$-10s %2$-10s %3$-10s]: %4",
new Data(record.getMillis(),
record.getSourceMethodName(),
record.getSourceClassName(),
formatMessage(record)
));
如何使用String.format()
字符串格式化成表檢查this page。
是的,這是一個解決方案,但可以通過MessageFormat#格式來實現嗎?看看這個:http://download.oracle.com/javase/6/docs/api/java/text/MessageFormat.html#format(java.lang.Object [],java.lang.StringBuffer,java.text。 FieldPosition)有第三個參數pos,其描述如下:如果需要,輸入:一個對齊字段。輸出時:對齊字段的偏移量。 – l245c4l 2011-05-03 11:11:00
FieldPosition與輸出對齊無關。這是一個處理/更改這些{}字段以及相應位置和格式的類。 MessageFormat類只是另一種做法,你可以用'String.format'完成。你爲什麼要使用它? – Joao 2011-05-03 11:54:06
那麼我讀過的地方,它可以比手動追加數據和javadocs更快,因爲它是不可理解的。好吧,只是出於好奇:) – l245c4l 2011-05-04 16:13:12