package com.xypower.mpmaster;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;


public class LogFormatter extends Formatter {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static String getLevelName(Level level) {
        int levelInt = level.intValue();
        if (levelInt >= 1000) {
            return "E";
        } else if (levelInt >= 900) {
            return "W";
        } else if (levelInt >= 700) {
            return "I";
        } else if (levelInt >= 500) {
            return "D";
        } else {
            return "V";
        }
    }

    @Override
    public String format(LogRecord record) {
        String message = formatMessage(record);
        return String.format(sdf.format(new Date(record.getMillis())) + " [%s] %s\n",
                // ecord.
                getLevelName(record.getLevel()), message);
    }

    /**
     * 将{@link LogFormatter}实例指定为{@link Logger}的输出格式
     * @param logger
     * @return always logger
     */
    public static Logger installFormatter(Logger logger){
        if(null != logger){
            /** 禁用原输出handler,否则会输出两次 */
            logger.setUseParentHandlers(false);
            ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setFormatter(new LogFormatter());
            logger.addHandler(consoleHandler);
        }
        return logger;
    }

}
