Reputation: 980
I am using java.util.logging. I want 2 logs - one for time measurements and one for all other things. The problem is that the timer logger still logs everything, how do I tell it to log only what I send to logTime method?
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";
}
}
}
Upvotes: 1
Views: 429
Reputation: 262534
private static Logger globalLogger = Logger.getLogger(Main.class.getName());
private static Logger timingLogger = Logger.getLogger(Main.class.getName());
That is the same logger, and as a result, your configuration gets mixed up.
You have to give two different names to Logger.getLogger
to get two different loggers.
Upvotes: 3