Configure log4j to log into the user file at runtime

Can someone tell me how I can configure log4j to log into a specific file that I specify at runtime. The name and path of the log file are generated at runtime, and the application must register on that particular file.

Typically, the file entries in the log4j.properties file point to the log file that the application will use. However, in this case, I would like to read the path to the log file from the command line and enter this specific file.

How can i achieve this?

+47
java log4j
Aug 24 '09 at 18:49
source share
4 answers

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"); } } 
+51
Aug 24 '09 at 18:54
source share

You can also do this from the log4j.properties file. Using the sample file below, I 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 be set in two different ways:

  • As a command line, the system property is passed to java "-Dlogfile.name = {logfile}"
  • In a java program, directly setting the system property (BEFORE calling log4j).

    System.setProperty ("logfile.name", "path name / log file string");

+78
Feb 10 2018-11-11T00:
source share

Can also be done using these properties in the log4j.properties file

 log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.maxFileSize=5000KB log4j.appender.logfile.maxBackupIndex=5 log4j.appender.logfile.File=/WebSphere/AppServer/profiles/Custom01/error.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p [%t] %C %M %c{1}:%L - %m%n 
0
Jul 11 '16 at 11:40
source share

It worked and was tested

 // setting up a FileAppender dynamically... SimpleLayout layout = new SimpleLayout(); RollingFileAppender appender = new RollingFileAppender(layout,"file-name_with_location",true); appender.setMaxFileSize("20MB"); logger.addAppender(appender); 
0
May 2, '17 at 11:44
source share



All Articles