1.2. 創建一個logger
包 java.util.logging提供了日志的功能,可以使用類似于下面的代碼來創建一個logger:
import java.util.logging.Logger;
private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName());
1.3.?Level
Log的等級反映了問題的嚴重程度。Level類用于決定哪些信息被寫入到log中。下面是一個按嚴重程度的降序排列的Log Level:
SEVERE (highest)
WARNING
INFO
CONFIG
FINE
FINER
FINEST
除此之外,您還可以使用OFF或ALL這兩個level來關閉log或打開所有log。
下面這行代碼是將logger設置為記錄INFO級別:
LOGGER.setLevel(Level.INFO);
1.4.?Handler
每個logger可以設置多個Handler。
Handler的作用是接收logger的信息,并將其以合適的格式發送到合適的地方。
一個Handler可以用setLevel(Level.OFF)來關閉,用setLevel(...)開啟。
JDK提供了幾個標準的handler,例如:
ConsoleHandler: 將log信息寫到Console
FileHandler: 將log信息寫到文件中
超過INFO(包含INFO)的信息將自動被寫入到Console中。
1.5.?Formatter
每個Handler的輸出都可以使用一個formatter來配置
已有的formatter:
SimpleFormatter 將所有的log信息以文本格式編排
XMLFormatter 生成XML格式的log信息
您還可以自定義Formatter,下面的這個示例Formatter可以將log信息用html的格式包裝:
package logging;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
//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
buf.append("
");buf.append("
");if (rec.getLevel().intValue() >= Level.WARNING.intValue())
{
buf.append("");
buf.append(rec.getLevel());
buf.append("");
} else
{
buf.append(rec.getLevel());
}
buf.append("
");buf.append("
");buf.append(calcDate(rec.getMillis()));
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
buf.append("
");buf.append("
\n");return buf.toString();
}
private String calcDate(long millisecs)
{
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
}
// This method is called just after the handler using this
// formatter is created
public String getHead(Handler h)
{
return "\n
\n" + (new Date()) + "\n\n\n\n"
+ "
+ "
TimeLog Message\n";}
// This method is called just after the handler using this
// formatter is closed
public String getTail(Handler h)
{
return "
\n \n\n";}
}
1.6.?Log Manager
log manager的職責是創建和管理logger,并負責維護log配置。
使用LogManager.setLevel(String name, Level level)方法,我們可以為一個包或一組包設置logging level。例如,我們可以將所有logger的logging
level設為Level.FINE:
LogManager.getLogManager().setLevel("logging", Level.FINE)
1.7.?Best Practices
使用被logged的那個類的名稱為logger命名是一種很好的方法,這種方法可以使程序員更好地查看日志和管理logger,同時,這也是Logging API推薦的一種方式。
2. 示例
您可以在項目“de.vogella.logger”中找到這個例子:
創建你自己的formatter:
package logging;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
//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
buf.append("
");buf.append("
");if (rec.getLevel().intValue() >= Level.WARNING.intValue())
{
buf.append("");
buf.append(rec.getLevel());
buf.append("");
} else
{
buf.append(rec.getLevel());
}
buf.append("
");buf.append("
");buf.append(calcDate(rec.getMillis()));
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
buf.append("
");buf.append("
\n");return buf.toString();
}
private String calcDate(long millisecs)
{
SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(millisecs);
return date_format.format(resultdate);
}
// This method is called just after the handler using this
// formatter is created
public String getHead(Handler h)
{
return "\n
\n" + (new Date()) + "\n\n\n\n"
+ "
+ "
TimeLog Message\n";}
// This method is called just after the handler using this
// formatter is closed
public String getTail(Handler h)
{
return "
\n \n\n";}
}初始化logger
package logging;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class MyLogger {
static private FileHandler fileTxt;
static private SimpleFormatter formatterTxt;
static private FileHandler fileHTML;
static private Formatter formatterHTML;
static public void setup() throws IOException {
// Create Logger
Logger logger = Logger.getLogger("");
logger.setLevel(Level.INFO);
fileTxt = new FileHandler("Logging.txt");
fileHTML = new FileHandler("Logging.html");
// Create txt Formatter
formatterTxt = new SimpleFormatter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
// Create HTML Formatter
formatterHTML = new MyHtmlFormatter();
fileHTML.setFormatter(formatterHTML);
logger.addHandler(fileHTML);
}
}使用logger
package logging;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UseLogger {
// Always use the classname, this way you can refactor
private final static Logger LOGGER = Logger.getLogger(UseLogger.class
.getName());
public void writeLog() {
// Set the LogLevel to Severe, only severe Messages will be written
LOGGER.setLevel(Level.SEVERE);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
// Set the LogLevel to Info, severe, warning and info will be written
// Finest is still not written
LOGGER.setLevel(Level.INFO);
LOGGER.severe("Info Log");
LOGGER.warning("Info Log");
LOGGER.info("Info Log");
LOGGER.finest("Really not important");
}
public static void main(String[] args) {
UseLogger logger = new UseLogger();
try {
MyLogger.setup();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
logger.writeLog();
}
}