简体   繁体   中英

Creating a dynamic log4j output file

I am trying to make a log4j file using html layout. Heres my log4j files

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/htmlLayout.html

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Example
log4j.appender.FILE.layout.LocationInfo=true

This is static, but I want to make it such that my main method will pass this line

 log4j.appender.FILE.File=myfilepath/myfilename.html 

How can I do this? currently I was trying to use properties, but it deletes everything and only this line shows up.

Please Note that the log file path depends on the location from where the jar file of my project is being executed it will be like this

(jarDir)/logs/myfilename.html

You'll have to call the log4j configurator directly rather than being able to rely on the default initialisation behaviour. Name the properties file something other than log4j.properties so the default procedure doesn't find it, then in your code you can do

Properties props = new Properties();
// if MyClass is in package com.example, look for
// com/example/log4j-config.properties inside the jar
InputStream in = MyClass.class.getResourceAsStream("log4j-config.properties");
try {
  props.load(in);
} finally {
  in.close();
}

// override file location
props.setProperty("log4j.appender.FILE.File", "myfilepath/myfilename.html");

LogManager.resetConfiguration();
PropertyConfigurator.configure(props);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM