In Apache Log4J, is there a way to just create multiple log files on the fly rather than appending to a single log file?
I have a program where I would like to be able to separate each individual log message into its own log file.
So, if a class generates 10 ERROR
logs and 10 DEBUG
logs, within a single run of the program, then this should create 20 log files, and they could ideally be something like:
logoutput1
logoutput2
logoutput3
..etc
And each log file only has one line.
I am working on a project in which I would like to implement some offline capabilities - the idea is that we can have a third, external program that can read in these log files (and then react to them)
Is this possible with Log4j? How can this be done? thank!
source to share
Yes, you can use RoutingAppender. See this question for details: Log4j2: Dynamically Generating Log Files for Multiple Logs
source to share
Create your own file log file and create a new file every time it tries to write some log. The following code snippet might help you.
public class SingleLogMsgFileAppender extends FileAppender {
private String file = null;
private static long fileNo;
public SingleLogMsgFileAppender() {
super();
fileNo = 1;
}
@Override
protected void subAppend(LoggingEvent event) {
createNewFile(true);
synchronized (this) {
super.subAppend(event);
}
}
@Override
public void setFile(String file) {
this.file = file;
createNewFile(false);
}
public void createNewFile(boolean incrementFileNo) {
try {
String fileName = file + "testlogfile." + fileNo + ".log";
super.setFile(fileName);
super.activateOptions();
} catch (Exception e) {
e.printStackTrace();
}
if (incrementFileNo) {
fileNo++;
}
}
}
and here is the log4j config file
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CustomAppender" class="loga.randd.threads.log4j.SingleLogMsgFileAppender">
<param name="File" value="log/" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{MM_dd_yyyy HH_mm_ss}%m%n" />
</layout>
</appender>
<root>
<priority value="debug" />
<appender-ref ref="CustomAppender" />
</root>
</log4j:configuration>
source to share