gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:41:22 54 4
gpt4 key购买 nike

这是我面临的挑战:

我有一个 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>

有什么想法吗?

最佳答案

感谢@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>

关于java - Log4j2:如何为每个用户将日志写入单独的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25114526/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com