package cn.reghao.bnt.web.config.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.FileAppender;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 编程方式配置 logback，相当于 logback-spring-bak.xml 配置
 *
 * @author reghao
 * @date 2021-02-23 23:53:35
 */
public class LoggerConfig {
    private static final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    public static void initLogger(List<Appender<ILoggingEvent>> list) {
        String env = System.getProperty("spring.profiles.active");
        if (!"dev".equals(env)) {
            // TODO 非 dev 环境则禁止日志写入 console
        }

        Logger rootLogger = loggerContext.getLogger("ROOT");
        rootLogger.setAdditive(false);
        rootLogger.setLevel(Level.INFO);
        list.forEach(iLoggingEventAppender -> {
            iLoggingEventAppender.start();
            rootLogger.addAppender(iLoggingEventAppender);
        });
    }

    public static Appender<ILoggingEvent> fileAppender() {
        PatternLayoutEncoder layoutEncoder = new PatternLayoutEncoder();
        layoutEncoder.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
        layoutEncoder.setContext(loggerContext);
        layoutEncoder.start();

        FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
        fileAppender.setFile("file");
        fileAppender.setEncoder(layoutEncoder);
        fileAppender.setContext(loggerContext);
        fileAppender.start();
        return fileAppender;
    }

    public static Appender<ILoggingEvent> consoleAppender() {
        PatternLayoutEncoder layoutEncoder = new PatternLayoutEncoder();
        layoutEncoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %c %M %L - %msg%n");
        layoutEncoder.setContext(loggerContext);
        layoutEncoder.start();

        ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
        consoleAppender.setEncoder(layoutEncoder);
        consoleAppender.setContext(loggerContext);
        consoleAppender.start();
        return consoleAppender;
    }
}
