直接上代码:
1.创建FIlter,往 MDC 里面追加内容
@WebFilter
@Component
public class LogBackFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// LOGSTASH 日志附加信息追加
addMDC(request,response,chain);
}
@Override
public void destroy() {
rmMDC();
}
private void addMDC(ServletRequest request, ServletResponse response, FilterChain chain){
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String uuid = UUID.randomUUID().toString();
MDC.put(LogConstant.REQUEST_ID, uuid);
String remoteIp = request.getRemoteAddr();
MDC.put(LogConstant.REQUEST_RM_IP, remoteIp);
String remoteHost = request.getRemoteHost();
MDC.put(LogConstant.REQUEST_RM_HOST, remoteHost);
String uri = httpServletRequest.getRequestURI();
MDC.put(LogConstant.REQUEST_URI, uri);
AuthUser authUser = UserContext.getCurrentUser();
if(authUser!=null){
MDC.put(LogConstant.REQUEST_USER_ID, authUser.getId());
}
}
private void rmMDC(){
MDC.remove(LogConstant.REQUEST_ID);
MDC.remove(LogConstant.REQUEST_RM_IP);
MDC.remove(LogConstant.REQUEST_RM_HOST);
MDC.remove(LogConstant.REQUEST_URI);
MDC.remove(LogConstant.REQUEST_USER_ID);
}
}
2.logback配置:文章来源:https://www.toymoban.com/news/detail-608005.html
includeMdcKeyName 标签 追加 mdc中的key文章来源地址https://www.toymoban.com/news/detail-608005.html
<!--输出到elk的LOGSTASH-->
<appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<!-- 配置elk日志收集 配饰的是 LOGSTASH 的地址-->
<destination>${LOGSTASH_SERVER}</destination>
<encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
<providers>
<timestamp>
<timeZone>UTC</timeZone>
</timestamp>
</providers>
<includeCallerData>true</includeCallerData>
<includeMdc>true</includeMdc>
<!-- MDC字段 -->
<includeMdcKeyName>X-Request-Id</includeMdcKeyName>
<includeMdcKeyName>X-Request-Uri</includeMdcKeyName>
<includeMdcKeyName>X-Request-UserId</includeMdcKeyName>
<includeMdcKeyName>X-Request-Rm-Ip</includeMdcKeyName>
<includeMdcKeyName>X-Request-Rm-Host</includeMdcKeyName>
<!--自定义字段 区分项目-->
<customFields>{"appName":"${APP_NAME}"}</customFields>
</encoder>
</appender>
到了这里,关于logback 自定义log字段(MDC)推送到logstash(spring boot + logback+ logstash)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!