EmmyTie
EmmyTie

Reputation: 11

Log4j2 Using class/logger name as a pattern for RoutingAppender

I am trying to set up individual logging files per class in a certain package. The closest solution I've found is to use the RoutingAppender and to have a special getLogger for those certain classes that adds to a ThreadContext when that getLogger method is called. However, this solution isn't creating any new log files. I've been reading stackoverflow entries and log4j2 documentation, but can't understand where I'm going wrong. Here's some of entries/documentation that I've looked at

Can anyone help me understand why I don't have any of the className log files?

Here's the relevant excepts from my log4j2.xml:

    <Routing name="Routing">
        <Routes pattern="$${ctx:className}">
            <Route>
                <File name="testCaseLog"
                    fileName="${ctx:className}.log">
                    <PatternLayout
                        pattern="%d{HH:mm:ss} %-5p [%t] %c{1} - %m%n" />
                </File>
            </Route>
        </Routes>
    </Routing>
</Appenders>
<Loggers>
    (other loggers)
    <Root level="info">
        <AppenderRef ref="stdout" />
        <AppenderRef ref="Routing"/>
    </Root>
</Loggers>

Here's the bit from my logger function in a myUtils class

public static Logger getLogger(String className) {
    ThreadContext.put("className", className);

    //This is using the slf4j LoggerFactory. I'm starting to think this might be the problem, but I can't get away from slf4j
    Logger log = LoggerFactory.getLogger(className);

    return log;
}

Here's a call from within one of the classes that needs it's own log file:

    private final static Logger log = myUtils.getLogger(OpenTest.class.getName());

Upvotes: 1

Views: 4832

Answers (1)

Remko Popma
Remko Popma

Reputation: 36834

Can you try adding another Route section to the Routes element you already have, with key="$${ctx:className}"?

        <Route key="$${ctx:className}">
            <File name="testCaseLog"
                fileName="${ctx:className}.log">
                <PatternLayout
                    pattern="%d{HH:mm:ss} %-5p [%t] %c{1} - %m%n" />
            </File>
        </Route>

Upvotes: 0

Related Questions