package com.fri.http.rest.logging;


import com.fri.http.rest.config.YXDefaultServerConfig;
import com.fri.http.rest.utils.TimeUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;


class YXLogFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
        String recordStr;
        recordStr =  record.getLevel() + ":" +
                "[" + record.getSourceClassName() + "." + record.getSourceMethodName() + "]" +
                "[" + record.getMillis() + "]"  +
                "[th-" + record.getThreadID() + "]" + ":" + record.getMessage()+"\n";
        return recordStr;
    }
}

/**
 * Created by zhangdahui on 2017/5/1.
 */
public class YXLogging {

    private static final HashMap<String, Logger> _logMap = new HashMap<String, Logger>();

    public static Logger CreateLogger(String name, Level level) throws IOException {

        if (_logMap.keySet().contains(name)) {
            return _logMap.get(name);
        }else{
            Logger log = Logger.getLogger(name);

            String dateTime = TimeUtils.currentDateAsString();
            String logFilePath = YXDefaultServerConfig.LOGGING_OUTPUT_FOLDER + '/' + name + '-' + dateTime + ".log";

            FileHandler fileHandler = new FileHandler(
                    logFilePath, // log file full path
                    YXDefaultServerConfig.LOGGING_FILE_SINGLE_SIZE, // log single file size
                    YXDefaultServerConfig.LOGGING_FILE_COUNT); // logging file count

            fileHandler.setFormatter(new YXLogFormatter());

            MemoryHandler m = new MemoryHandler(fileHandler, YXDefaultServerConfig.LOGGING_ENTRY_BUFFER, level);


            log.addHandler(m);
            _logMap.put(name, log);
            return log;
        }
    }

    public static Logger getLogger(String name){
        return _logMap.get(name);
    }

}

