0

我需要在每个 LoggingEvent(或 log4j2 中的 LogEvent)中为我的 ConsoleAppender 获取用户名参数。

迁移到 log4j2 时,如何在 log4j 中重新创建更改 CustomConsoleAppender 的 doAppend 方法的实现:

public class CustomConsoleAppender extends ConsoleAppender
{
    public void doAppend(LoggingEvent event)
    {
        String username = SecurityContextHelper.getLogonUsername();
        if (username != null)
            MDC.put("userId", username);
        else
            MDC.put("userId", "system");
        super.doAppend(event);
    }
}

然后使用模式在相应附加程序的 PatternLayout 中的 log4j2.properties 中检索该值:%X{userId}

4

1 回答 1

0

Found a solution here: https://stackoverflow.com/a/45039509/17913034

By using the LogEventFactory (see implementation details in solution 2 of the link above) and also replacing MDC with ThreadContext (because of log4j2):

public class MyLogEventFactory implements LogEventFactory {

@Override
public LogEvent createEvent(String loggerName, Marker marker, String fqcn, Level level, Message message,
        List<Property> properties, Throwable t) {
    { // In my case i wanted "log.error(new Exception(msg))"
      // to pass the exception properly to the event,
      // as if "log.error(msg, new Exception(msg))" was called.
        if (t == null && message instanceof ObjectMessage) {
            ObjectMessage msg = (ObjectMessage) message;
            t = msg.getThrowable();
        }
    }
    // my adjustments here:
    String username = SecurityContextHelper.getLogonUsername();
        if (username != null)
            ThreadContext.put("userId", username);
        else
            ThreadContext.put("userId", "system");
        return new Log4jLogEvent(loggerName, marker, fqcn, level, message, properties, t);
    }

}
于 2022-01-12T14:51:15.947 回答