2

I have a SpringBoot backend with logback configured. Authentication is achieved using a OncePerRequestFilter and setting the authentication in the SecurityContextHolder context.

My goal is to print the loggedUser username whenever logback prints an error. My attempt was to add a variable (${LOGGED_USER}) to the logback pattern and then set this variable in the OncePerRequestFilter using the code below:

     final Context context = (Context) LoggerFactory.getILoggerFactory();
     final JoranConfigurator configurator = new JoranConfigurator();
     configurator.setContext(context);
     context.putProperty("LOGGED_USER", username);
          try {
                configurator.doConfigure(Objects.requireNonNull(getClass().getResource("/logback.xml")));
          } catch (JoranException e) {
                logger.error("Error while configuring logger", e);
          }

This works fine in localhost environment. When in production, however, when an error is generated the logger outputs several times, showing every logged user name. It seems to me that my code is creating a new logger context for every request and they are all outputting the error at the same time. I am out of ideas and looking for help!

Thanks in advance

1 Answers1

1

Did you try using Mapped Diagnostic Context to store the username. Access it in the pattern as %X{LOGGED_USER}

final Context context = (Context) LoggerFactory.getILoggerFactory();
 final JoranConfigurator configurator = new JoranConfigurator();
 configurator.setContext(context);
 MDC.put("LOGGED_USER", username);
      try {
            configurator.doConfigure(Objects.requireNonNull(getClass().getResource("/logback.xml")));
      } catch (JoranException e) {
            logger.error("Error while configuring logger", e);
      }

EDIT-

Since you are using OncePerRequestFilter, this answer by another user may help you