2017-12-11 3 views
0

Test이라는 클래스가 있으며 Thread에서 확장됩니다. 각 테스트 스레드마다 내 자신의 로그 파일이 작성되도록 log4j2를 구성하는 방법. 스레드에 대한 log4j2 구성

나는이 작업을 수행하기 위해 노력하고있어 :

public class Test extends Thread { 

private String name; 

private Logger LOGGER; 

public Test(String name) { 
    this.name=name; 
} 

@Override 
public void run() { 

    System.setProperty("taskLogFolder", Global.getInstance().getLogRoot().toString()); 
    System.setProperty("taskLogName", name); 

    LoggerContext loggerContext = Configurator.initialize(name, new File(Global.getInstance().getAppRoot()+WEB_INF_DIR+"taskLog4j2.xml").toString()); 

    LOGGER = loggerContext.getLogger(name); 

    for(int i=0;i<100;i++) { 
     LOGGER.info(LOGGER.getName()+" "+i); 
    } 

    //LOGGER.info(LOGGER.getName()); 

} 

}

그러나 시작시 하나 개의 파일이 출력됩니다.

new Test("task-8").start(); 
new Test("task-2").start(); 
new Test("task-3").start(); 
new Test("task-4").start(); 
new Test("task-5").start(); 
new Test("task-6").start(); 
new Test("task-7").start(); 

이전에 log4j를 사용 했었지만 그 방법은 잘 모르겠습니다.

내가 뭘 잘못하고 있니?

taskLog4j2.xml 파일 :

<?xml version="1.0" encoding="UTF-8"?> 
<Configuration status="info" monitorInterval = "30"> 

    <Properties> 
     <Property name="pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n</Property> 
    </Properties> 

    <Appenders> 
     <RollingFile name="fileLogger" fileName="${sys:taskLogFolder}/${sys:taskLogName}.log" filePattern="${sys:taskLogFolder}/${sys:taskLogName}-%d{yyyy-MM-dd}.log"> 
      <PatternLayout> 
       <pattern>${pattern}</pattern> 
      </PatternLayout> 
      <Policies> 
       <TimeBasedTriggeringPolicy interval="1" modulate="true" /> 
      </Policies> 
     </RollingFile> 

     <Console name="console" target="SYSTEM_OUT"> 
      <PatternLayout pattern="${pattern}" /> 
     </Console> 
    </Appenders> 

    <Loggers> 
     <Root level="info" additivity="false"> 
      <appender-ref ref="console" /> 
      <appender-ref ref="fileLogger" /> 
     </Root> 
     <Logger name="com.test.*" level="info"> 
      <appender-ref ref="fileLogger" level="info" /> 
     </Logger> 
    </Loggers> 

</Configuration> 

@Sudheera 응답

2017-12-12 22:22:46,942 task-3 ERROR Unable to invoke factory method in class org.apache.logging.log4j.core.appender.RollingFileAppender for element RollingFile: java.lang.IllegalStateException: No factory method found for class org.apache.logging.log4j.core.appender.RollingFileAppender java.lang.IllegalStateException: No factory method found for class org.apache.logging.log4j.core.appender.RollingFileAppender 
at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.findFactoryMethod(PluginBuilder.java:229) 
at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:134) 
at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:958) 
at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:898) 
at org.apache.logging.log4j.core.appender.routing.RoutingAppender.createAppender(RoutingAppender.java:271) 
at org.apache.logging.log4j.core.appender.routing.RoutingAppender.getControl(RoutingAppender.java:255) 
at org.apache.logging.log4j.core.appender.routing.RoutingAppender.append(RoutingAppender.java:225) 
at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156) 
at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129) 
at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120) 
at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84) 
at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:448) 
at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:433) 
at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:417) 
at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:403) 
at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:63) 
at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:146) 
at org.apache.logging.log4j.spi.AbstractLogger.tryLogMessage(AbstractLogger.java:2116) 
at org.apache.logging.log4j.spi.AbstractLogger.logMessageSafely(AbstractLogger.java:2100) 
at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:1994) 
at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1966) 
at org.apache.logging.log4j.spi.AbstractLogger.info(AbstractLogger.java:1303) 
at com.test.Test.run(Test.java:20) 
+0

[다른 로그 파일에 여러 스레드를 기록하는 방법] (https://stackoverflow.com/questions/8355847/how-to-log-multiple-threads-in-different-log-files) – clinomaniac

+0

@clinomaniac 그것은 log4j 1.에 해당합니다. Log4j2를 사용합니다. – Tsyklop

답변

3

에 대한 사용자 정의 이름 조회를위한의 log4j 설정 플러그인을 작성하고 라우터 구성을 통해 사용할 수 있습니다. 여기에 고정 된 코드가 있습니다. log4j 설정 컨텍스트에서 스레드 이름을 찾기 위해 Log4jThreadLookup 클래스를 추가했습니다. 이 클래스가 클래스 경로에서 사용 가능한지 확인하십시오. 구성 파일과 Test 클래스도 변경했습니다.

Log4jThreadLookup 클래스

package com.test; 

import org.apache.logging.log4j.core.LogEvent; 
import org.apache.logging.log4j.core.config.plugins.Plugin; 
import org.apache.logging.log4j.core.lookup.StrLookup; 

@Plugin(name = "thread", category = StrLookup.CATEGORY) 
public class Log4jThreadLookup implements StrLookup { 

    public String lookup(String key) { 
     return Thread.currentThread().getName(); 
    } 

    public String lookup(LogEvent event, String key) { 
     return event.getThreadName(); 
    } 

} 

구성

<?xml version="1.0" encoding="UTF-8"?> 
<Configuration status="info" monitorInterval = "30"> 

    <Properties> 
     <Property name="pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [thread-id %T] %l - %msg%n</Property> 
    </Properties> 

    <Appenders> 
     <Routing name="Routing"> 
      <Routes pattern="$${thread:threadName}"> 
       <Route> 
        <RollingFile name="logFile-${thread:threadName}" 
           fileName="logs/tasks-${thread:threadName}.log" filePattern="logs/tasks-${thread:threadName}-%d{yyyy-MM-dd}.log"> 
         <PatternLayout> 
          <pattern>${pattern}</pattern> 
         </PatternLayout> 
         <Policies> 
          <TimeBasedTriggeringPolicy interval="1" modulate="true" /> 
         </Policies> 
        </RollingFile> 
       </Route> 
      </Routes> 
     </Routing> 
     <Console name="console" target="SYSTEM_OUT"> 
      <PatternLayout pattern="${pattern}" /> 
     </Console> 
    </Appenders> 

    <Loggers> 
     <Root level="info" additivity="false"> 
      <appender-ref ref="console" /> 
      <appender-ref ref="Routing" /> 
     </Root> 
     <Logger name="com.test.*" level="info"> 
      <appender-ref ref="Routing" level="info" /> 
     </Logger> 
    </Loggers> 

</Configuration> 

테스트 클래스

package com.test; 

import org.apache.logging.log4j.LogManager; 
import org.apache.logging.log4j.Logger; 

public class Test extends Thread { 

    private static final Logger LOGGER = LogManager.getLogger(Test.class); 
    private final String name; 

    public Test(String name) { 
     this.name = name; 
    } 

    @Override 
    public void run() { 
     Thread.currentThread().setName(name); 

     for (int i = 0; i < 100; i++) { 
      LOGGER.info(LOGGER.getName() + " " + i); 
     } 

    } 
} 

output

+0

.xml 파일은 어디에 위치해야합니까? – Tsyklop

+0

나는 그것을 시도 사용자 - 작동하지 않습니다. – Tsyklop

+0

머리에 붙여 넣기 오류가 있습니다. – Tsyklop