logback统一扩展打印自定义属性字段的方式

记录下采用logback统一扩展打印自定义属性字段的方式, 通常打印日志,自己可以采用拼字符串的方式,或者String.format等格式化字符串方式。但其实logback还提供了一种比较好玩的方式MDC. 特使是针对那些格式比较统一的日志,在WEB中用一个拦截器就可以实现, 比如要统一打印登录的用户:
程序代码 程序代码

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.MDC;

public class UserServletFilter implements Filter {

  private final String USER_KEY = "username";
  
  public void destroy() {
  }

  public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {

    boolean successfulRegistration = false;

    HttpServletRequest req = (HttpServletRequest) request;    
    Principal principal = req.getUserPrincipal();
    // Please note that we could have also used a cookie to
    // retrieve the user name

    if (principal != null) {
      String username = principal.getName();
      successfulRegistration = registerUsername(username);
    }

    try {
      chain.doFilter(request, response);
    } finally {
      if (successfulRegistration) {
        MDC.remove(USER_KEY);
      }
    }
  }

  public void init(FilterConfig arg0) throws ServletException {
  }
  

  /**
   * Register the user in the MDC under USER_KEY.
   *
   * @param username
   * @return true id the user can be successfully registered
   */
  private boolean registerUsername(String username) {
    if (username != null && username.trim().length() > 0) {
      MDC.put(USER_KEY, username);
      return true;
    }
    return false;
  }
}


loback 的日志配置中,增加自己需要的字段,类似如下:
程序代码 程序代码

<Pattern>%-4r [%thread] %-5level C:%X{username} - %msg%n</Pattern>


参考资料:
https://logback.qos.ch/manual/mdc.html

除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
[本日志由 yihaomen 于 2019-09-16 02:31 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 1 | 引用: 0 | 查看次数: -
回复回复yhm[2019-09-20 09:30 AM | del]
电商专用快递网站www.dh5u.com单号无忧
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.