Log4j2 代码配置log 自定义输出日志到指定文件

通过java代码配置log4j2配置log,做到将log输出到不同的log日志文件中。

写了一个工具类,通过参数控制日志文件名称。

public class LogUtil {
    /**
     * 日志打印的目录
     */
    private static final String LOGDIR = "/logs";
    /**
     * Logger Context对象
     */
    private static final LoggerContext CTX = (LoggerContext) LogManager.getContext(false);
    /**
     * Configuration对象
     */
    private static final Configuration CONFIG = CTX.getConfiguration();

    /**
     * 启动一个动态的logger
     *
     * @param loggerName
     * @return
     */
    private static void start(String loggerName) {
        //创建一个展示的样式:PatternLayout,   还有其他的日志打印样式。
        PatternLayout layout = PatternLayout.newBuilder()
                .withConfiguration(CONFIG)
                .withPattern("[%d] [%thread] %-5p ${appName} ${sys:PID} %c %m%n")
                .build();

        //单个日志文件大小
        TimeBasedTriggeringPolicy tbtp = TimeBasedTriggeringPolicy.newBuilder()
                .withInterval(1)
                .withModulate(true)
                .build();
        // 大小分割
        SizeBasedTriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("200 MB");
        CompositeTriggeringPolicy policyComposite = CompositeTriggeringPolicy.createPolicy(tbtp, tp);

        String loggerDir = LOGDIR + File.separator + "quartz-" + loggerName;
        DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
                .withMax("30")
                .withConfig(CONFIG)
                .build();
        ThresholdFilter infoFilter = ThresholdFilter.createFilter(Level.INFO, Filter.Result.ACCEPT, Filter.Result.DENY);
        ThresholdFilter errorFilter = ThresholdFilter.createFilter(Level.ERROR, Filter.Result.ACCEPT, Filter.Result.NEUTRAL);
        RollingFileAppender appender =  RollingFileAppender.newBuilder()
                .withFileName(loggerDir + ".log")
                .withFilePattern(loggerDir + ".%d{yyyy-MM-dd}.%i.log.gz")
                .withAppend(true)
                .withPolicy(policyComposite)
                .withStrategy(strategy)
                .setName(loggerName)
                .setFilter(infoFilter)
                .setFilter(errorFilter)
                .setLayout(layout)
                .setConfiguration(CONFIG)
                .build();
        appender.start();
        CONFIG.addAppender(appender);

        AppenderRef ref = AppenderRef.createAppenderRef(loggerName, null, null);
        AppenderRef[] refs = new AppenderRef[]{ref};
        LoggerConfig loggerConfig = LoggerConfig.createLogger(false,
                Level.INFO, loggerName, "true", refs, null, CONFIG, null);
        loggerConfig.addAppender(appender, Level.INFO, null);
        CONFIG.addLogger(loggerName, loggerConfig);
        CTX.updateLoggers();
    }

    /**
     * 使用完关闭动态创建的logger,避免内存不够用或者文件打开太多
     *
     * @param loggerName
     * @return
     */
    public static void stop(String loggerName) {
        synchronized (CONFIG) {
            CONFIG.getAppender(loggerName).stop();
            CONFIG.getLoggerConfig(loggerName).removeAppender(loggerName);
            CONFIG.removeLogger(loggerName);
            CTX.updateLoggers();
        }
    }

    /**
     * 获取Logger
     *
     * @param loggerName
     * @return
     */
    public static Logger getLogger(String loggerName) {
        synchronized (CONFIG) {
            if (!CONFIG.getLoggers().containsKey(loggerName)) {
                start(loggerName);
            }
        }
        return LogManager.getLogger(loggerName);
    }

}

工具类使用:

private Logger log = LogUtil.getLogger(this.getClass().getName());

你可能感兴趣的:(Log4j2 代码配置log 自定义输出日志到指定文件)