How can I customize the log file name in log4j2?
To customize the log file name of Log4j2, you can achieve this through either configuring the file or using code.
<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>
In the above configuration, fileName specifies the initial name of the log file, and filePattern specifies the naming rule for rolling log files. %d represents the date format, and %t represents the thread name.
- Application using a Rolling Random Access File Appender
- A file appender that automatically creates new log files as needed.
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();
}
}
In the code above, the fileName specifies the initial name of the log file, while filePattern specifies the naming rule for the rolling log files. %d represents the date format and %t represents the thread name.