我正在使用带有MemoryHandler的java.util.logging编写Java Server应用程序。
当应用程序终止时,如何让MemoryHandler将数据推送到文件?
我尝试添加ShutDownHook并手动将数据推送到文件,但是当达到“hook”时,似乎已经删除了日志处理程序。
这是我的代码:
public class example implements Runnable{
static {
// Set upp logging
// Adding a MemoryHandler
FileHandler fileHandler = null;
MemoryHandler memoryHandler;
try {
fileHandler = new FileHandler("myapp.log");
fileHandler.setLevel(Level.ALL);
} catch (IOException e) {
e.printStackTrace();
}
memoryHandler = new MemoryHandler( fileHandler, 100, Level.SEVERE);
Logger rootLogger = Logger.getLogger("");
rootLogger.addHandler(memoryHandler);
}
public static void main(String[] args) throws Exception {
Thread serverThread = new Thread(new example());
serverThread.setDaemon(false);
serverThread.start();
}
public void run() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// This is execute when application are shutting down.
//
// MemoryHandler are not not in the handlers list
for (Handler handler: Logger.getLogger("").getHandlers())
{
System.out.println("Looping handlers");
if (handler.getClass() == MemoryHandler.class)
{
System.out.println("Memoryhandler found");
//This never happens.
((MemoryHandler)handler).push();
}
}
});
try {
// ALOT OF STUFF
}
catch (Exception ex)
{
}
}
}
请指教!