📄 e400. creating a custom formatter for a logger handler.txt
字号:
A logger's handler uses a formatter to write a log record out to the log file. The java.util.logging package provides two formatters; see e399 Setting the Formatter of a Logger Handler for more information. However, the logging package allows you to create custom formatters.
This example creates a custom formatter that prints one line for each log record and surrounds the log data with HTML tags.
// This custom formatter formats parts of a log record to a single line
class MyHtmlFormatter extends Formatter {
// This method is called for every log records
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
// Bold any levels >= WARNING
if (rec.getLevel().intValue() >= Level.WARNING.intValue()) {
buf.append("<b>");
buf.append(rec.getLevel());
buf.append("</b>");
} else {
buf.append(rec.getLevel());
}
buf.append(' ');
buf.append(rec.getMillis());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
// This method is called just after the handler using this
// formatter is created
public String getHead(Handler h) {
return "<HTML><HEAD>"+(new Date())+"</HEAD><BODY><PRE>\n";
}
// This method is called just after the handler using this
// formatter is closed
public String getTail(Handler h) {
return "</PRE></BODY></HTML>\n";
}
}
Here's some code to use the custom formatter:
// Get the logger
Logger logger = Logger.getLogger("com.mycompany");
try {
// Create a file handler that uses the custom formatter
FileHandler fh = new FileHandler("mylog.html");
fh.setFormatter(new MyHtmlFormatter());
logger.addHandler(fh);
} catch (IOException e) {
}
// Log some messages
logger.setLevel(Level.ALL);
logger.severe("my severe message");
logger.info("my info message");
logger.entering(this.getClass().getName(), "myMethod", new Object[]{"para1", "para2"});
Here's the output from the example code above:
<HTML><HEAD>Fri Jan 11 13:32:57 PST 2002</HEAD><BODY><PRE>
<b>SEVERE</b> 1010784777240 my severe message
INFO 1010784777390 my info message
FINER 1010784777400 ENTRY para1 para2
</PRE></BODY></HTML>
Related Examples
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -