Search code examples
javalogginglog4jslf4jmdc

slfj4 logging - MDC.put function not printing anything


I am trying to print the username who has logged in along with their id in the logs using slfj4 MDC class. Here is my code, please tell me where i am wrong.

JAVA FILE -

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public classResponse getuser(@PathVariable("user_id") Integer user_id, @RequestParam(value = "department_id", required = false) Integer department_id) {
    JSONObject response = null;
    String username = getUserName();
    logger.debug("Testing MDC.");
    MDC.put("FirstName", "First");
    MDC.put("LastName", "Last");
    logger.info(":::ServiceContoller.getuser starts for userid" + user_id);
    logger.info(":::ServiceContoller.getCreateEnvironment:Ends for username" + username);
    try {
        response = classServiceImpl.getUser1(username, user_id, department_id);
        logger.info("Sending Environment details - {}", response);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return new ClassResponse(Constants.STR_ERROR, "Error getting USERDetails");
    }
    return new ClassResponse(Constants.STR_SUCCESS, response);
}

XML PROPERTIES FILE - logback.xml -

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <layout>
      <Pattern>%-4r [%thread] %-5level C:%X{FirstName} N:%X{LastName} - %m%n</Pattern>
    </layout>       
  </appender>

  <root> 
  <level value="info" />
    <appender-ref ref="CONSOLE"/>
  </root>  
</configuration>

Please tell me what more I need to have or where I am wrong. Any help appreciated. Thank you in advance.


Solution

  • Can you try this.. https://logback.qos.ch/manual/appenders.html

    <configuration>
    
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
          <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
        </encoder>
      </appender>
    
      <root level="DEBUG">
        <appender-ref ref="STDOUT" />
      </root>
    </configuration>