0
我正在使用java.util.logging。 我想要2個日誌 - 一個用於時間測量,另一個用於所有其他事情。 問題是,定時器記錄器仍然記錄一切,我如何告訴它只記錄我發送給logTime方法的內容?Java Logger記錄一切
import configurations.ConfigReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
import configurations.Time;
import main.Main;
/**
* Created by giladba on 27/01/2016.
*/
public class LogManager {
private static final String LOGS_PATH = (String) ConfigReader.get(ConfigReader.Field.LOGS);
private static Logger globalLogger = Logger.getLogger(Main.class.getName());
private static Logger timingLogger = Logger.getLogger(Main.class.getName());
static {
initLoggers(globalLogger, (String) ConfigReader.get(ConfigReader.Field.ST_VIEW));
initLoggers(timingLogger, ConfigReader.get(ConfigReader.Field.ST_VIEW) + "_timing");
timingLogger.setUseParentHandlers(false);
}
public synchronized static void log(String message) {
globalLogger.info(message);
}
public synchronized static void logTime(String action, long time1, long time2) {
timingLogger.info(Time.getTimeNowFormatted() + action + "\t\t : " + (time2-time1) + " ms");
}
/**
* Initializes the logger.
* @throws SecurityException
* @throws IOException
*/
private static void initLoggers(Logger curLog, String name) throws SecurityException {
FileHandler procHandler = null;
try {
File file = new File(LOGS_PATH);
if(!file.exists())
file.mkdirs();
procHandler = new FileHandler(LOGS_PATH + name + "_log.out", 2048000, 20, true);
} catch (IOException e) {
e.printStackTrace();
}
procHandler.setFormatter(new MyFormatter());
procHandler.setLevel(Level.INFO);
curLog.addHandler(procHandler);
curLog.setUseParentHandlers(true);
curLog.info("\n");
curLog.info("--------" + (new SimpleDateFormat("dd-MM-yy_HH:mm:ss")).format(new Date()) + "--------");
}
/**
* simple naked formatter for the log files.
* @author jeremieg
*
*/
static class MyFormatter extends Formatter {
@Override
public String format(LogRecord arg0) {
return arg0.getMessage() + "\n";
}
}
}
你的日誌配置在哪裏?除此之外:您可能想要決定是否使用像slf4j或log4j/log4j2這樣的不同框架更適合您。 – Marged
的確切換到像SLF4J這樣的現代框架。 – Stefan
你指的是哪種配置?如果你正在談論ConfigReader,它所做的就是返回一個路徑到我想放置日誌的目錄。 –