'Log in both text and JSON format in a Spring Boot application

I have a Spring Boot application and for the log we are using the Logback library. As per project requirements it is necessary to add the log in JSON format so that it is possible to obtain metrics. This log must be added to the existing one and will be used in the same methods and for same level, but will log other information.

How is this situation handled? I add an example for clarity:

public class UserService {
    
private final Logger logger = LoggerFactory.getLogger(UserService.class);

public UserResponse getUser(UserRequest userRequest) {

    User user = userRepository.findById(userRequest.getId());

    //text log
    logger.info("User " + user.getFullName().toString() + " found");

    //json log to add
    LogInfo logInfo = new LogInfo(LocalDateTime.now(), getClass().getName(), user.getName(), user.getSurname(), ...);
    newLogger.info(logInfo);
    
    return new UserResponse(user);
    }
}


Solution 1:[1]

Add dependencies

<dependencies>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.6</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback.contrib</groupId>
        <artifactId>logback-json-classic</artifactId>
        <version>0.1.5</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback.contrib</groupId>
        <artifactId>logback-jackson</artifactId>
        <version>0.1.5</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.3</version>
    </dependency>
</dependencies>

Add file logback.xml has content

<appender name="json" class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
        <jsonFormatter
            class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
            <prettyPrint>true</prettyPrint>
        </jsonFormatter>
        <timestampFormat>yyyy-MM-dd' 'HH:mm:ss.SSS</timestampFormat>
    </layout>
</appender>

<logger name="jsonLogger" level="TRACE">
    <appender-ref ref="json" />
</logger>

Call logger

Logger logger = LoggerFactory.getLogger("jsonLogger");
logger.debug("Debug/INFO/ERROR message");

Solution 2:[2]

you will need to proper configure the logback plugin adding a business required template, you can inspire from: https://mathieularose.com/logback-json

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James Graham
Solution 2 Ionut Adrian Ene