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 的日志配置中,增加自己需要的字段,类似如下:
%-4r [%thread] %-5level C:%X{username} - %msg%n


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

上一篇: django-uuslug汉字转拼音出现的小问题,可能是BUG.
下一篇: Redis docker启动并开启远程密码连接服务

Avatar

home 评论于: 2020-01-23

My brother suggested I might like this web site. 
He used to be totally right. This publish actually made my day.
You can not consider simply how much time I had spent 
for this information! Thanks!

Avatar

yhm 评论于: 2019-09-20

电商专用快递网站www.dh5u.com单号无忧
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章来源于互联网, 若有侵权, 联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布文章.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号