JavaBlog.fr / Java.lu DEVELOPMENT,Java,Libray,Tools Java : Log4j overwite the file path on runtime

Java : Log4j overwite the file path on runtime

Hi,

After my previous posts concerning Java: Log4j Concepts and Explanations and Java: Log4j in practice, I would expose a solution to overwrite the file path on runtime.

Libraries needed : commons-lang3-3.1.jar, commons-logging-1.1.1.jar and log4j-1.2.15.jar.

MainApp.java

01package com.ho.log4j.test2;
02 
03import java.io.FileInputStream;
04import java.io.InputStream;
05import java.util.Properties;
06 
07import org.apache.log4j.LogManager;
08import org.apache.log4j.PropertyConfigurator;
09 
10public class MainApp {
11 
12    private final static String LOG4J_FILENAME = "log4jInjector.properties";
13    private final static String BUSINESS_LOG_FILE_KEY = "BUSINESS_LOG_FILE";
14    private final static String TECHNICAL_LOG_FILE_KEY = "TECHNICAL_LOG_FILE";
15    private static LogUtil logUtil = null;
16 
17    /**
18     * Main
19     * @param args
20     */
21    public static void main(String[] args){
22 
23        try{
24            if(args==null || args.length==0){
25                System.out.println("Usage : MainApp configfilepath");
26                System.out.println("configfilepath : path to the configuration file config.properties containing the parameters");
27                return;
28            }
29 
30            Properties prop = new Properties();
31            {
32                InputStream input;
33                String filename = args[0];
34                System.out.println("********Loading of configuration file named "+filename+"********");
35                input = new FileInputStream(filename);
36                prop.load(input);
37            }
38 
39            {
40                InputStream log4ConfigStream = null;
41                try {
42                    log4ConfigStream = LogUtil.class.getResourceAsStream(LOG4J_FILENAME);
43                    Properties props = new Properties();
44                    props.load(log4ConfigStream);
45                    props.setProperty("log4j.appender.BUSINESSLOGFILE.File", prop.getProperty(BUSINESS_LOG_FILE_KEY));
46                    props.setProperty("log4j.appender.TECHNICALLOGFILE.File", prop.getProperty(TECHNICAL_LOG_FILE_KEY));
47                    LogManager.resetConfiguration();
48                    PropertyConfigurator.configure(props);
49                } catch (Exception ex) {
50                    ex.printStackTrace(System.out);
51                    throw new RuntimeException("Error in the LogUtil.init() method...");
52                } finally {
53                    if (log4ConfigStream != null) {
54                        try {
55                            log4ConfigStream.close();
56                        } catch (Exception ex) {
57                            ex.printStackTrace(System.out);
58                        }
59                    }
60                }
61            }
62 
63            // Initialisation du logger
64            logUtil = new LogUtil();
65 
66            logUtil.log("************************** log trace 1 ************************");
67            logUtil.logError("******** log trace 2 ERROR ********");
68 
69        }catch(Throwable th){
70            if(logUtil !=null){
71                logUtil.logException(th);
72            }else{
73                th.printStackTrace();
74            }
75        }
76    }
77}

Config.properties

BUSINESS_LOG_FILE=D\:\\...\\... \\data\\results\\InjectorBusiness.log
TECHNICAL_LOG_FILE=D\:\\...\\...\\data\\results\\InjectorTechnical.log

LogUtil.java

01package com.ho.log4j.test2;
02 
03import org.apache.commons.lang3.exception.ExceptionUtils;
04 
05public class LogUtil {
06 
07 
08    private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogUtil.class);
09 
10    // ----------------------------------------------------------- CONSTRUCTOR
11    public LogUtil() { }
12 
13    // ------------------------------------------------------ PUBLIC FUNCTIONS
14    public void log(String str){
15        if(str !=null){
16            log.info(str);
17        }else{
18            log.info("");
19        }
20    }
21 
22    public void logException(Throwable ex){
23        Throwable th = ExceptionUtils.getRootCause(ex);
24        if(th == null){
25            log.error(ex);
26        }else{
27            log.error(th);
28        }
29    }
30 
31    public void logError(String str){
32        if(str !=null){
33            log.error(str);
34        }else{
35            log.error("");
36        }
37    }
38}

log4jInjector.properties

log4j.rootCategory=ALL,CONSOLE,TECHNICALLOGFILE

log4j.logger.com.ho.log4j.test2.LogUtil=INFO,BUSINESSLOGFILE

#------------------- CONSOLE --------------------------
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %m%n
log4j.appender.CONSOLE.Threshold=INFO

#------------------- FILE --------------------------
log4j.appender.TECHNICALLOGFILE=org.apache.log4j.RollingFileAppender
log4j.appender.TECHNICALLOGFILE.File=injectortech.log
log4j.appender.TECHNICALLOGFILE.MaxFileSize=30MB
log4j.appender.TECHNICALLOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.TECHNICALLOGFILE.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c - %m%n
log4j.appender.TECHNICALLOGFILE.Threshold=ALL

#------------------- BUSINESSLOGFILE --------------------------
log4j.appender.BUSINESSLOGFILE=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.BUSINESSLOGFILE.File=${catalina.base}/logs/Injector.log
log4j.appender.BUSINESSLOGFILE.File=injector.log
log4j.appender.BUSINESSLOGFILE.DatePattern='.'yyy-MM-dd-HH
log4j.appender.BUSINESSLOGFILE.MaxFileSize=30MB
log4j.appender.BUSINESSLOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.BUSINESSLOGFILE.Threshold=ALL
log4j.appender.BUSINESSLOGFILE.Append=true
log4j.appender.BUSINESSLOGFILE.layout.ConversionPattern=%-d{MMM dd HH:mm:ss} %-5p %c %M %m%n

Execute the MainApp class with the following program argument “C:\…\test_log4j\src\com\ho\log4j\test2\Config.properties”.

So the resuts would be the generation of log files named:
InjectorBusiness.log:

oct. 04 00:06:32 INFO com.ho.log4j.test2.LogUtil log ************************** log trace 1 ************************
oct. 04 00:06:32 ERROR com.ho.log4j.test2.LogUtil logError ******** log trace 2 ERROR ********

…and InjectorTechnical.log:

00:06:32,074 INFO [main] com.ho.log4j.test2.LogUtil - ************************** log trace 1 ************************
00:06:32,078 ERROR [main] com.ho.log4j.test2.LogUtil - ******** log trace 2 ERROR ********

That’s all!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post