|
| 1 | +/* |
| 2 | + * Copyright (C) 2009-2019 Slava Semushin <slava.semushin@gmail.com> |
| 3 | + * |
| 4 | + * This program is free software; you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU General Public License as published by |
| 6 | + * the Free Software Foundation; either version 2 of the License, or |
| 7 | + * (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with this program; if not, write to the Free Software |
| 16 | + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 17 | + */ |
| 18 | +package ru.mystamps.web.support.spring.security; |
| 19 | + |
| 20 | +import org.slf4j.MDC; |
| 21 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 22 | + |
| 23 | +import javax.servlet.FilterChain; |
| 24 | +import javax.servlet.ServletException; |
| 25 | +import javax.servlet.http.HttpServletRequest; |
| 26 | +import javax.servlet.http.HttpServletResponse; |
| 27 | +import java.io.IOException; |
| 28 | + |
| 29 | +public class UserMdcLoggingFilter extends OncePerRequestFilter { |
| 30 | + private static final String USER_ID = "userId"; |
| 31 | + |
| 32 | + @Override |
| 33 | + protected void doFilterInternal( |
| 34 | + HttpServletRequest request, |
| 35 | + HttpServletResponse response, |
| 36 | + FilterChain filterChain) |
| 37 | + throws ServletException, IOException { |
| 38 | + |
| 39 | + Integer userId = SecurityContextUtils.getUserId(); |
| 40 | + if (userId != null) { |
| 41 | + MDC.put(USER_ID, userId.toString()); |
| 42 | + } |
| 43 | + |
| 44 | + try { |
| 45 | + filterChain.doFilter(request, response); |
| 46 | + } finally { |
| 47 | + MDC.remove(USER_ID); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments