I wonder if there is demand (´ ・ ω ・ `) If you want to hook the timing when a log file is generated or opened in FileAppender
, the class that inherits FileAppender
and overrides setFile
is changed to log4j.Appender
. Specify.
For example, if you want to switch the log file for each date, more specifically, sample.log.20180211
for the log of February 11, 2018, and sample. For the log of February 12, 2018. If you want to record in log.20180212
, prepare the following original file and log4j.properties
.
log4j.properties
log4j.logger.sample=DEBUG, SAMPLE
log4j.appender.SAMPLE=sample.logger.SampleFileAppender
log4j.appender.SAMPLE.File=C:\\logging\\sample.log
log4j.appender.SAMPLE.Append=true
log4j.appender.SAMPLE.layout=org.apache.log4j.PatternLayout
log4j.appender.SAMPLE.layout.ConversionPattern=%d %p %m %n
SampleFileAppender.java
package sample.logger;
import org.apache.log4j.FileAppender;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SampleFileAppender extends FileAppender {
@Override
synchronized public void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
Path path = Paths.get(fileName);
String baseName = path.getFileName() + "." + DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
super.setFile(Paths.get(path.getParent().toString(), baseName).toString(), append, bufferedIO, bufferSize);
}
}
If you think about it carefully, DailyRollingFileAppender
is enough for this purpose (´ ・ ω ・ `) I'm sorry it's not a good sample (´ ・ ω ・ `)
Recommended Posts