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);
}
}
CodePudding user response:
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" >
<layout >
<jsonFormatter
>
<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");
CodePudding user response:
you will need to proper configure the logback plugin adding a business required template, you can inspire from: https://mathieularose.com/logback-json