我希望将我的字符串添加为app中每条日志消息的前缀。我的意思是,我有几个java应用程序,我想要一个在消息中有一些前缀,如:
DATE, INFO(or other), [sample] (-->this is my added string) , rest of standard message
我看过几个教程,但没有一个能适合我。我已经将依赖包含在pom中了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
你有什么技巧或简单的解决方案吗?要编写某种包装器或配置类?
答案 0 :(得分:1)
映射诊断上下文(MDC)日志记录允许您设置与当前线程关联的属性,以便SLF4J(通过您的记录器实现库)可以使用每个日志记录语句记录这些属性,而无需指定它。 所以你需要的是把你的前缀文本放在MDC中。如果您正在使用Spring MVC,那么一种方法是实现HandlerInterceptor。
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoggingInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MDC.put("PREFIX", "your text");
return true;
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MDC.clear();
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
MDC.clear();
}
}
import com.tigerit.kai.education.util.LoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class BeanConfiguration {
@Bean
public LoggingInterceptor loggingHandlerInterceptor() {
return new LoggingInterceptor();
}
@Bean
public WebMvcConfigurerAdapter webConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loggingHandlerInterceptor());
}
};
}
}
最后在application.properties
中添加以下内容logging.pattern.console=%d %-4r [%thread] %-5level PREFIX=%X{PREFIX} - %msg%n