Search code examples
javaspringspring-bootlogback

Add value from database to logback log message


I have a Spring Boot application that is using logback for application logs. Now I've added support for logz.io to centralize the logs from multiple machines to one place. The problem is that I can't know which log is coming from which machine.

In the application database, I have a unique token that is unique for every machine where the application is running. My idea is to pre-append that token value to every log message so I can differentiate which client is sending which logs.

I can access the token value through a method in the repository that extends the JpaRepository. Logback configuration is done through the logback.xml

Edit: Each client uses its own H2 database where the value is stored.

Example of a message I currently have:

2020-03-26 07:58:13,702 [scheduling-1] INFO n.g.service.ScheduledBotService - Test message

To be:

UniqueToken123 2020-03-26 07:58:13,702 [scheduling-1] INFO n.g.service.ScheduledBotService - Test message


Solution

  • I try Thread Context in log4j2 and it seems work for me.

    Test Code

    public class AppTest {
    
        private Logger logger = LogManager.getLogger(AppTest.class);
    
        @Test
        public void testMaxFromIntegerList(){
    
            String uniqueToken = getTokenFromJpa();
    
            ThreadContext.put("uniqueToken", uniqueToken); 
            logger.info("Message Set uniqueToken");
    
            //remove after using
            ThreadContext.remove("uniqueToken");
            logger.info("Message Clear uniqueToken");
        }
    
        // dummy code.
        private String getTokenFromJpa() {
            return "UniqueToken123";
        }
    
    }
    

    Log4j2 Config.
    Be notice that in your PatternLayout, use %X{key} to include the specified key.

    appender.rolling.layout.pattern = %X{uniqueToken} %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    

    Content in logFile.

    UniqueToken123 2020-03-26 18:18:56 INFO  AppTest:30 - Message Set uniqueToken
     2020-03-26 18:18:56 INFO  AppTest:33 - Message Clear uniqueToken
    

    You can get more about Thread Context from here

    I hope it would help.