Log4j2:如何将日志写入每个用户的单独文件?

时间:2014-08-04 08:29:00

标签: java logging configuration log4j log4j2

这是我面临的挑战:

我有一个servlet程序。我需要将每个用户的日志写入以该用户命名的文件夹。 像这样:

    // stores message to David folder
    // /root_path/David/logfile.log
    logger.error(MarkerManager.getMarker("David"), "Error happened");

    // stores message to Mark folder
    // /root_path/Mark/logfile.log                 
    logger.error(MarkerManager.getMarker("Mark"), "Something is broken");

在我的例子中,我使用了标记。但我真的不知道标记是否适合这项任务。

一般来说,我的appender应该像RollingRandomAccessFile appender一样。 我想appender的配置看起来像这样:

     <RollingRandomAccessFile name="rollingFile"
                 fileName="logs/{markerName ?????}/movie-db.log"
                 filePattern="logs/log-%d{yyyy-MM-dd}-%i.log.zip"
                 append="false"
                 immediateFlush="false"
                 ignoreExceptions="true">
        <PatternLayout pattern="%d{ISO8601} %level{length=5} [%thread] %logger - %msg%n"/>
        <Policies>
            <SizeBasedTriggeringPolicy size="25 MB"/>
            <TimeBasedTriggeringPolicy />
        </Policies>
        <DefaultRolloverStrategy max="10"/>
    </RollingRandomAccessFile>

有什么想法吗?

2 个答案:

答案 0 :(得分:22)

感谢@Remko Popma回答我弄清楚了。以下是解决方案示例:

package com.bondarenko.tmp;

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

public class TestRouting {

private final static Logger log = LogManager.getLogger(TestRouting.class);

public static void main(String[] args) {
    ThreadContext.put("logFileName", "David");
    log.info("Error happened");

    ThreadContext.put("logFileName", "Mark");
    log.info("Something is broken");

    ThreadContext.remove("logFileName");
}
}

和log4j.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">

<Appenders>
    <Console name="consoleAppender" target="SYSTEM_OUT">
        <!--SHORT PATTERN-->
        <PatternLayout pattern="%d{ABSOLUTE} %level{length=5} [%thread] %logger{1} - %msg%n"/>
        <!--ROBUST PATTERN
        <PatternLayout pattern="%d{ISO8601} %level{length=5} [%thread] %logger - %msg%n"/>-->
    </Console>

    <Routing name="RoutingAppender">
        <Routes pattern="${ctx:logFileName}">
            <Route>
                <RollingFile name="Rolling-${ctx:logFileName}"
                             fileName="logs/${ctx:logFileName}"
                             filePattern="logs/${ctx:logFileName}.%i.log.gz">
                    <PatternLayout pattern="%d{ABSOLUTE} %level{length=5} [%thread] %logger{1} - %msg%n"/>
                    <SizeBasedTriggeringPolicy size="512" />
                </RollingFile>
            </Route>

            <!-- By having this set to ${ctx:logFileName} it will match when filename
                 is not set in the context -->
            <Route ref="consoleAppender" key="${ctx:logFileName}"/>
        </Routes>
    </Routing>

</Appenders>

<Loggers>
    <Logger name="com.bondarenko.tmp" level="info" additivity="false">
        <AppenderRef ref="RoutingAppender"/>
    </Logger>
</Loggers>

答案 1 :(得分:2)

Log4j2 FAQ page有一个使用RoutingAppender实现此目的的例子。