package org.nl.config.lucene;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.rolling.RollingFileAppender;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class DynamicLogger {
    String logPath;//日志存储路径
    public DynamicLogger(String logPath) {
        this.logPath = logPath;
    }
    //对外暴露日志对象：每次拿的对象从内存里拿，没有再构建
    private static Map<String,Logger> container = new HashMap<>();
    public Logger getLogger(String dynamicName) {
        Logger logger = container.get(dynamicName);
        if(logger != null) {
            return logger;
        }
        logger = build(dynamicName);
        container.put(dynamicName,logger);
        return logger;
    }
    //构建Logger对象，给Logger指定appender
    private Logger build(String dynamicName) {
        RollingFileAppender runTaskAppender =new DynamicLogAppender().getAppender(this.logPath,dynamicName);
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = context.getLogger(dynamicName);
        logger.addAppender(runTaskAppender);
        return logger;
    }
}
