编写自定义格式化程序扩展java.util.logging.Formatter
类并String format(LogRecord)
根据您的需要实现该方法。例如,以下格式化程序仅显示日志消息(如果正在记录异常,则显示可抛出的堆栈跟踪):
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
class CustomRecordFormatter extends Formatter {
@Override
public String format(final LogRecord r) {
StringBuilder sb = new StringBuilder();
sb.append(formatMessage(r)).append(System.getProperty("line.separator"));
if (null != r.getThrown()) {
sb.append("Throwable occurred: "); //$NON-NLS-1$
Throwable t = r.getThrown();
PrintWriter pw = null;
try {
StringWriter sw = new StringWriter();
pw = new PrintWriter(sw);
t.printStackTrace(pw);
sb.append(sw.toString());
} finally {
if (pw != null) {
try {
pw.close();
} catch (Exception e) {
// ignore
}
}
}
}
return sb.toString();
}
}
这是你如何使用它:
import java.util.logging.ConsoleHandler;
import java.util.logging.Logger;
class A {
private static final Logger LOGGER = Logger.getLogger(A.class.getName());
static {
CustomRecordFormatter formatter = new CustomRecordFormatter();
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(formatter);
LOGGER.addHandler(consoleHandler);
}
public void doSomething() {
LOGGER.info("something happened");
}
}