Created
January 17, 2023 19:26
-
-
Save rajeevshukla/d0ea16b2f0af8b09b13b61d4d5c9bd6d to your computer and use it in GitHub Desktop.
Spring AOP Aspect to log ip address and User Id
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Aspect | |
@Component | |
public class LoggingAspect { | |
@Before("execution(* com.example.controller.*.*(..))") | |
public void before(JoinPoint joinPoint) { | |
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); | |
MDC.put("ip", request.getRemoteAddr()); | |
MDC.put("userId", request.getHeader("userId")); | |
} | |
@After("execution(* com.example.controller.*.*(..))") | |
public void after() { | |
MDC.remove("ip"); | |
MDC.remove("userId"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this works like a charm!! thanks mate. just check for the null point on
RequestContextHolder.getRequestAttributes()