Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

configure log4j to log to custom file at runtime

Tags:

java

log4j

Can anyone please guide me as to how I can configure log4j to log to a specific file that I specify at run-time.The name and path of the log file are generated at run-time and the application must log to that particular file.

Generally file appender entries in the log4j.properties file points to the log file that will be used by the application.However in this case I would like to read the log file path from the command line and log to that particular file.

How can I achieve this ?

like image 622
Fell Avatar asked Aug 24 '09 18:08

Fell


People also ask

How do I change the log4j configuration at runtime?

Use LogManager. resetConfiguration(); to clear the current config and configure it again. Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config).

How do you set log file path in log4j properties dynamically?

System. setProperty("{my. log", "C:/logfile. log");

How do you create a new log file for each time the application runs log4j?

File with system properties name and some prefix text if you want. This will create a log file with current date time, something like this Log4jDemoApp-dd-MM-yyyy-hh-mm-ss. log every time we run the application. It will create the new file because for every run we are setting current date stamp in system properties.


1 Answers

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:

  1. As a command line, system property passed to java "-Dlogfile.name={logfile}"
  2. 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");

like image 165
jmq Avatar answered Sep 24 '22 06:09

jmq