package org.nl.config.lucene;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.charset.Charset;

public class DynamicLogAppender {
    /**
     * 通过传入的动态名字,动态设置appender
     * @param dynamicName
     * @return
     */
    public RollingFileAppender getAppender(String oldLogPath,String dynamicName) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        RollingFileAppender appender = new RollingFileAppender();
        //appender的name属性
        appender.setName(dynamicName);
        appender.setContext(context);

        //设置文件名
        appender.setFile(new File(oldLogPath, dynamicName + "\\" + DateUtil.format(new DateTime(),"yyyy-MM-dd")+".log").getAbsolutePath());
        //设置日志文件输出格式
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(context);
        encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
        encoder.setCharset(Charset.forName("UTF-8"));
        encoder.start();

        //设置日志记录器的滚动策略
        TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
        policy.setFileNamePattern(oldLogPath+dynamicName+".%d{yyyy-MM-dd}.log");
        policy.setParent(appender); //设置父节点是appender
        policy.setContext(context);
        policy.start();

        //加入下面两个节点
        appender.setRollingPolicy(policy);
        appender.setEncoder(encoder);
        appender.start();
        return appender;
    }
}
