首先,您在哪里定义了记录器,以及从哪个类\方法尝试调用它?有一个工作的例子,新鲜出炉:
public class LoggingTester {
private final Logger logger = Logger.getLogger(LoggingTester.class
.getName());
private FileHandler fh = null;
public LoggingTester() {
//just to make our log file nicer :)
SimpleDateFormat format = new SimpleDateFormat("M-d_HHmmss");
try {
fh = new FileHandler("C:/temp/test/MyLogFile_"
+ format.format(Calendar.getInstance().getTime()) + ".log");
} catch (Exception e) {
e.printStackTrace();
}
fh.setFormatter(new SimpleFormatter());
logger.addHandler(fh);
}
public void doLogging() {
logger.info("info msg");
logger.severe("error message");
logger.fine("fine message"); //won't show because to high level of logging
}
}
在你的代码中,你忘记了定义格式化程序,如果你需要一个简单的格式化程序,你可以像我上面提到的那样做,但是还有另一种选择,你可以自己格式化它,有一个例子(只需插入它而不是这行fh.setFormatter(new SimpleFormatter())下面的代码):
fh.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
SimpleDateFormat logTime = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(record.getMillis());
return record.getLevel()
+ logTime.format(cal.getTime())
+ " || "
+ record.getSourceClassName().substring(
record.getSourceClassName().lastIndexOf(".")+1,
record.getSourceClassName().length())
+ "."
+ record.getSourceMethodName()
+ "() : "
+ record.getMessage() + "\n";
}
});
或任何其他你喜欢的修改。希望它有帮助。