简体   繁体   English

将每个用户/每个请求的Java servlet中的日志分组

[英]Group the logging inside a java servlet per user / per request

I have a simple servlet that does some calculations, and logs the intermediate results to a file using slf4j as the facade and a simple logging binder (also from slf4j) to log to the file. 我有一个简单的servlet,它进行一些计算,并将中间结果记录到文件中,使用slf4j作为外观,并使用一个简单的日志记录绑定程序(也来自slf4j)记录到文件中。 This works fine, but when multiple users are sending requests simultaneously, their logs get interwoven with each other. 这可以正常工作,但是当多个用户同时发送请求时,他们的日志会相互交织。 Below is a dummy example to show the problem: the logging from both user alice and bob gets mixed up: 下面是一个显示问题的虚拟示例:来自用户alice和bob的日志混合在一起:

log: phase1 of user alice
log: phase2 of user alice
log: phase1 of user bob
log: phase3 of user alice
log: phase2 of user bob
log: phase3 of user bob
...

This is really troublesome if the amount of users involved and the complexity of the log statements increases. 如果涉及的用户数量和日志语句的复杂性增加,这确实很麻烦。

A possible solution is to create a logfile for each user, and when a request enters by user X (this can be detected by my code), append it to logfile X. The problem is I don't see how to do this with simple logging. 一种可能的解决方案是为每个用户创建一个日志文件,然后当用户X输入一个请求时(我的代码可以检测到该请求),将其追加到日志文件X中。问题是我看不到如何简单地执行此操作记录。 Is is possible, and if not, is there another way? 有可能,如果没有,还有其他方法吗?

您可以将每个用户阶段的条目存储在某种结构中,然后在上一个阶段结束时或在发生错误时(如果发生错误)立即将所有阶段记录为单个日志条目。

You might want to look at the "MDC" (Mapped Diagnostic Context) class in SLF4J (other logging frameworks also support this). 您可能需要查看SLF4J中的“ MDC”(映射的诊断上下文)类(其他日志记录框架也支持此类)。

It allows you to set custom logging context data and then you can get that data to appear in your messages. 它允许您设置自定义日志上下文数据,然后可以将该数据显示在消息中。

For example, you could do... 例如,您可以...

import org.slf4j.MDC;

...
    private static final USER_NAME_MDC_KEY = "USRKEY";

    servlet method {
        MDC.put(USER_NAME_MDC_KEY, user.getUserId());

        ...rest of logic...

    }

If you have a pattern set up like this... 如果您设置了这样的模式...

        <PatternLayout pattern="[UID=%X{USRKEY}] %d{HH:mm} [%t] %-level %c{1} - %m%n" />

...then each line in your log will contain... ...那么日志中的每一行都将包含...

[UID=<whatever has been set in the MDC>]

You could then GREP your logs for the particular user Id in order to get the messages logged just for them. 然后,您可以对特定用户ID的日志进行GREP,以便只为他们记录消息。

(I think this is sort of what you wanted, I might be wrong!) (我认为这是您想要的,我可能错了!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM