2015-08-17 152 views

回答

2

Log4j 2當前支持使用XML,JSON或YAML進行配置。儘管在不久的將來可能會支持屬性文件,但語法肯定會與Log4j 1不同。

3

也許這可以幫助您?

如何在具有特定配置文件的代碼中重新配置log4j2? 請看下面的例子。請注意,此LoggerContext類不屬於公共API,因此您的代碼可能會與任何次要版本發生衝突。

// import org.apache.logging.log4j.core.LoggerContext; 

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false); 
File file = new File("path/to/a/different/log4j2.xml"); 


// this will force a reconfiguration 
context.setConfigLocation(file.toURI());** 
0

這裏我解決了同樣的問題:

的web.xml

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 

    <context-param> 
     <param-name>isLog4jContextSelectorNamed</param-name> 
     <param-value>false</param-value> 
    </context-param> 

    <!-- ... and so on --> 

</web-app> 

LoggerHelper.java

import java.io.File; 
    import org.apache.logging.log4j.LogManager; 
    import org.apache.logging.log4j.core.LoggerContext; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 

    public final class LoggerHelper { 

     public static Logger INSTANCE; 

     public static void initialize() {  
     String  fileName = "<PATH>/log4j.xml"; 
     LoggerContext context = (LoggerContext)LogManager.getContext(false); 

     context.setConfigLocation(new File(fileName).toURI()); 
     INSTANCE = LoggerFactory.getLogger(LoggerHelper.class); 

     String logMessage = String.format("Initialized (%s).", fileName); 
     System.out.println(logMessage); 
     INSTANCE.info(logMessage); 
     } 

    }