log4j2

log4j2怎么自定义日志文件名

小亿
331
2023-12-27 19:38:34
栏目: 编程语言

要自定义Log4j2的日志文件名,可以通过配置文件或者代码方式来实现。

  1. 通过配置文件方式: 在log4j2的配置文件中,可以使用<RollingRandomAccessFile>或者<RollingFile>节点来定义日志文件的名称。例如:
<RollingRandomAccessFile name="FileLogger" fileName="logs/mylog.log" filePattern="logs/mylog-%d{MM-dd-yyyy}.log.gz">
    <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    <Policies>
        <TimeBasedTriggeringPolicy />
    </Policies>
</RollingRandomAccessFile>

上述配置中,fileName指定了日志文件的初始名称,filePattern指定了滚动日志文件的命名规则。%d表示日期格式,%t表示线程名。

  1. 通过代码方式: 在Java代码中,可以使用RollingRandomAccessFileAppender或者RollingFileAppender来定义日志文件的名称。例如:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.*;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Log4j2CustomFileNameExample {

    public static void main(String[] args) {
        // 使用代码方式配置Log4j2
        Configuration configuration = createLogConfiguration();
        Configurator.initialize(configuration);

        // 获取Logger
        Logger logger = LogManager.getLogger(Log4j2CustomFileNameExample.class);
        logger.info("This is a custom log message");
    }

    private static Configuration createLogConfiguration() {
        ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

        // 创建Appender
        AppenderComponentBuilder appenderBuilder = builder.newAppender("FileLogger", "RollingRandomAccessFile")
                .addAttribute("fileName", "logs/mylog.log")
                .addAttribute("filePattern", "logs/mylog-%d{MM-dd-yyyy}.log.gz");

        // 创建Layout
        LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n");

        // 添加Appender和Layout到Root Logger
        builder.add(appenderBuilder)
                .add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("FileLogger").addAttribute("level", Level.INFO)))
                .add(layoutBuilder);

        return builder.build();
    }
}

上述代码中,fileName指定了日志文件的初始名称,filePattern指定了滚动日志文件的命名规则。%d表示日期格式,%t表示线程名。

0
看了该问题的人还看了