我编写了独立的java工具。下面是我的记录器实现代码。我在下面的代码中面临一个问题。每当我调用ZRToolLogger.getLogger时,都会创建一个新文件。我需要在单个文件中维护日志信息。怎么解决这个问题?
我不知道以下实施是正确还是错误。如果错了,请告诉我另一种解决方法。
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class ZRToolLogger{
public static Logger getInfoLogger(String loggerName)
{
LogManager logManager = LogManager.getLogManager();
Logger logger = Logger.getLogger(loggerName);
logger.setUseParentHandlers(false);
FileHandler fh = null;
try{
fh = new FileHandler(ZRToolConstants.CTX_PATH+"/logs/log.%u.txt", true);
}
catch(IOException e)
{
}
logManager.addLogger(logger);
ZRToolLogFormatter formatterTxt = new ZRToolLogFormatter();
if(fh != null)
{
fh.setFormatter(formatterTxt);
}
logger.addHandler(fh);
return logger;
}
private static class ZRToolLogFormatter extends Formatter
{
public ZRToolLogFormatter()
{
super();
}
@Override
public String format(LogRecord log)
{
return log.getLevel() + ":" + formatMessage(log)+"\n";
}
}
}
感谢。
答案 0 :(得分:2)
你必须使fh静态。
public class ZRToolLogger{
public static FileHandler fh;
public static Logger getInfoLogger(String loggerName)
{
LogManager logManager = LogManager.getLogManager();
Logger logger = Logger.getLogger(loggerName);
logger.setUseParentHandlers(false);
if (ZRToolLogger.fh = null)
{
try{
ZRToolLogger.fh = new FileHandler(ZRToolConstants.CTX_PATH+"/logs/log.%u.txt", true);
}
catch(IOException e)
{
}
}
logManager.addLogger(logger);
ZRToolLogFormatter formatterTxt = new ZRToolLogFormatter();
if(ZRToolLogger.fh != null)
{
ZRToolLogger.fh.setFormatter(formatterTxt);
}
logger.addHandler(fh);
return logger;
}
private static class ZRToolLogFormatter extends Formatter
{
public ZRToolLogFormatter()
{
super();
}
@Override
public String format(LogRecord log)
{
return log.getLevel() + ":" + formatMessage(log)+"\n";
}
}
}