logback统一扩展打印自定义属性字段的方式
By:Roy.LiuLast updated:2019-09-16
记录下采用logback统一扩展打印自定义属性字段的方式, 通常打印日志,自己可以采用拼字符串的方式,或者String.format等格式化字符串方式。但其实logback还提供了一种比较好玩的方式MDC. 特使是针对那些格式比较统一的日志,在WEB中用一个拦截器就可以实现, 比如要统一打印登录的用户:
loback 的日志配置中,增加自己需要的字段,类似如下:
参考资料:
https://logback.qos.ch/manual/mdc.html
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
From:一号门
Previous:django-uuslug汉字转拼音出现的小问题,可能是BUG.
COMMENTS