Skip to content

Instantly share code, notes, and snippets.

@rajeevshukla
Created January 17, 2023 19:26
Show Gist options
  • Save rajeevshukla/d0ea16b2f0af8b09b13b61d4d5c9bd6d to your computer and use it in GitHub Desktop.
Save rajeevshukla/d0ea16b2f0af8b09b13b61d4d5c9bd6d to your computer and use it in GitHub Desktop.
Spring AOP Aspect to log ip address and User Id
@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");
}
}
@ea241832
Copy link

ea241832 commented Aug 8, 2024

this works like a charm!! thanks mate. just check for the null point on RequestContextHolder.getRequestAttributes()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment