要自定义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
表示线程名。
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
表示线程名。