package fr.insee.rmes.config;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.logging.log4j.web.Log4jServletContextListener;
import org.apache.logging.log4j.web.Log4jWebSupport;

public class Log4j2ServletContextListener implements ServletContextListener {

	private String log4j2ConfigFile;

	private Log4jServletContextListener listener;

	public Log4j2ServletContextListener() {
		this.listener = new Log4jServletContextListener();
		try {
			this.getEnvironmentProperties();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		servletContextEvent.getServletContext().setInitParameter(Log4jWebSupport.LOG4J_CONFIG_LOCATION,
				log4j2ConfigFile);
		listener.contextInitialized(servletContextEvent);
	}

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		listener.contextDestroyed(servletContextEvent);
	}

	private void getEnvironmentProperties() throws IOException {
		Properties props = this.getProperties();
		String log4JExternalFile = props.getProperty("fr.insee.rmes.api.log.configuration");
		this.log4j2ConfigFile = "log4j2.xml";
		File f = new File(log4JExternalFile);
		if (f.exists() && !f.isDirectory()) {
			this.log4j2ConfigFile = String.format(log4JExternalFile);
		}
	}
	
	private Properties getProperties() throws IOException {
        Properties props = new Properties();
        props.load(getClass()
                .getClassLoader()
                .getResourceAsStream("rmes-api.properties"));
        File f = new File(String.format("%s/webapps/%s", System.getProperty("catalina.base"), "rmes-api.properties"));
        if(f.exists() && !f.isDirectory()) {
            FileReader r = new FileReader(f);
            props.load(r);
            r.close();
        }
        return props;
    }

}

@@ -1203,16 +1203,56 @@
 ties();%0A
+%09%09this.log4j2ConfigFile = %22log4j2.xml%22;%0A
 %09%09String
@@ -1252,27 +1252,27 @@
 %09String log4
-JEx
+jIn
 ternalFile =
@@ -1276,66 +1276,176 @@
 e = 
-props.getProperty(%22fr.insee.rmes.api.log.configuration%22);%0A
+String.format(%22%25s/webapps/%25s%22, System.getProperty(%22catalina.base%22), log4j2ConfigFile);%0A%09%09File f = new File(log4jInternalFile);%0A%09%09if (f.exists() && !f.isDirectory()) %7B%0A%09
 %09%09th
@@ -1462,36 +1462,132 @@
 onfigFile = 
-%22
 log4j
-2.xml%22
+InternalFile;%0A%09%09%7D%0A%09%09String log4JExternalFile = props.getProperty(%22fr.insee.rmes.api.log.configuration%22)
 ;%0A%09%09File f =
@@ -1576,32 +1576,33 @@
 tion%22);%0A%09%09File f
+2
  = new File(log4
@@ -1616,32 +1616,33 @@
 alFile);%0A%09%09if (f
+2
 .exists() && !f.
@@ -1632,32 +1632,33 @@
 2.exists() && !f
+2
 .isDirectory()) 

Update Log4j2ServletContextListener.java