Different log files for multiple threads using log4j2

I am running a Java application in which I call several threads, each of which has several unique names. Now I want to create several log files for each of them, and the name of the log files should be like stream names. Is this possible using log4j2. Help me write log4j2 configuration files.

Thanks in advance.

+1
source share
2 answers

This can be done using RoutingAppender. The FAQ page has a good configuration example.

+1
source

, RoutingAppender - . ${ctx: threadName}, "ctx" ThreadContext. , :

ThreadContext.put("threadName", Thread.currentThread().getName());

, . java.lang.Runnable , .

, , , "org.apache.logging.log4j.core.lookup.StrLookup" @Plugin PluginManager :

: ThreadLookup

package my.logging.package    
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 ThreadLookup implements StrLookup {

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

@Override
public String lookup(LogEvent event, String key) {
    return event.getThreadName() == null ? Thread.currentThread().getName()
            : event.getThreadName();
}

}    

: log4j2.xml(packages Configuration @Plugin PluginManager)

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" packages="my.logging.package">
    <Appenders>
        <Routing name="Routing">
            <Routes pattern="$${thread:threadName}">
                <Route>
                    <RollingFile name="logFile-${thread:threadName}"
                    fileName="logs/concurrent-${thread:threadName}.log" filePattern="logs/concurrent-${thread:threadName}-%d{MM-dd-yyyy}-%i.log">
                    <PatternLayout pattern="%d %-5p [%t] %C{2} - %m%n" />
                    <Policies>
                        <SizeBasedTriggeringPolicy size="50 MB" />
                    </Policies>
                    <DefaultRolloverStrategy max="100" />
                </RollingFile>
            </Route>
        </Routes>
    </Routing>
    <Async name="async" bufferSize="1000" includeLocation="true">
        <AppenderRef ref="Routing" />
    </Async>
</Appenders>
<Loggers>
    <Root level="info">
        <AppenderRef ref="async" />
    </Root>
</Loggers>

+3

All Articles