我希望将我的字符串作为前缀添加到应用程序中的每个日志消息中。我的意思是,我有几个 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>
你有什么技巧或简单的解决方案吗?编写某种包装器或配置类?
映射诊断上下文 (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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)