I use Spring Boot and Slf4j at my application. I need to log specific audit events. Auditing with JPA, Hibernate, or Spring Data JPA does not fit with my needs since I want to log service level audit instead of DB. So, I decided to use Markers with loggers and then persist them into DB.
However, how can I interrupt all log messages and filter the ones which has my audit markers? All in all, they should be logged into a file too as like the ones without markers.
Database Appender
Spring uses Logback as the underlying log framework.
You can create a logback-spring.xml
file in src/resources
and then configure your logger. There is the default FILE appender and you can add your DATABASE appender
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<springProperty name="spring.datasource.driverClassName" source="spring.datasource.driverClassName"/>
<springProperty name="spring.datasource.url" source="spring.datasource.url"/>
<springProperty name="spring.datasource.username" source="spring.datasource.username"/>
<springProperty name="spring.datasource.password" source="spring.datasource.password"/>
<appender name="DATABASE" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>${spring.datasource.driverClassName}</driverClass>
<url>${spring.datasource.url}</url>
<user>${spring.datasource.username}</user>
<password>${spring.datasource.password}</password>
</connectionSource>
</appender>
<logger name="AUDIT" level="INFO">
<appender-ref ref="FILE"/>
<appender-ref ref="DATABASE"/>
</logger>
</configuration>
Additional Information
You can use the mapped diagnostic context (MDC) to store global information that you want to add to every log entry:
MDC.put("username", SecurityContextHolder.getContext().getAuthentication().getName());
To have it in the output you have to add it to the log pattern. For example:
<Pattern>%X{username} - %m%n</Pattern>
Further reading
I recommend to read the logback manual to get more information about appenders and MDC:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.