Java Logger记录所有内容

时间:2016-02-15 07:27:42

标签: java logging java.util.logging

我正在使用java.util.logging。 我想要2个日志 - 一个用于时间测量,一个用于所有其他事情。 问题是计时器记录器仍记录所有内容,如何告诉它只记录我发送给logTime方法的内容?

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";
        }
    }
}

1 个答案:

答案 0 :(得分:2)

private static Logger globalLogger = Logger.getLogger(Main.class.getName());
private static Logger timingLogger = Logger.getLogger(Main.class.getName());

这是相同的记录器,因此,您的配置会混淆。

您必须为Logger.getLogger提供两个不同的名称才能获得两个不同的记录器。