configure log4j to log to custom file at runtime
You can also do this from the log4j.properties file. Using the sample file below I have added the system property ${logfile.name}:
# logfile is set to be a RollingFileAppender
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${logfile.name}
log4j.appender.logfile.MaxFileSize=10MB
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=[%-5p]%d{yyyyMMdd@HH\:mm\:ss,SSS}\:%c - %m%n
The log file name can then be set two different ways:
- As a command line, system property passed to java "-Dlogfile.name={logfile}"
-
In the java program directly by setting a system property (BEFORE you make any calls to log4j).
System.setProperty("logfile.name","some path/logfile name string");
Adapted from the log4j documentation:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;
public class SimpandFile {
static Logger logger = Logger.getLogger(SimpandFile.class);
public static void main(String args[]) {
// setting up a FileAppender dynamically...
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"your filename",false);
logger.addAppender(appender);
logger.setLevel((Level) Level.DEBUG);
logger.debug("Here is some DEBUG");
logger.info("Here is some INFO");
logger.warn("Here is some WARN");
logger.error("Here is some ERROR");
logger.fatal("Here is some FATAL");
}
}