Created
November 21, 2019 16:19
-
-
Save murateca/06233ceb24f5da07ee9ba58d54ad1720 to your computer and use it in GitHub Desktop.
Logging aspect for spring boot
This file contains hidden or 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
| import org.apache.logging.log4j.LogManager; | |
| import org.apache.logging.log4j.Logger; | |
| import org.aspectj.lang.ProceedingJoinPoint; | |
| import org.aspectj.lang.annotation.Around; | |
| import org.aspectj.lang.annotation.Aspect; | |
| import org.aspectj.lang.reflect.MethodSignature; | |
| import org.springframework.stereotype.Component; | |
| import org.springframework.util.StopWatch; | |
| @Aspect | |
| @Component | |
| public class LoggingAspect { | |
| private static final Logger LOGGER = LogManager.getLogger(LoggingAspect.class); | |
| @Around("execution(* com.demo.services..*(..)))") | |
| public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { | |
| MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature(); | |
| String className = methodSignature.getDeclaringType().getSimpleName(); | |
| String methodName = methodSignature.getName(); | |
| String[] parameterNames = methodSignature.getParameterNames(); | |
| Object[] args = proceedingJoinPoint.getArgs(); | |
| StringBuilder parameterInfo = new StringBuilder(); | |
| for (int i = 0; i < parameterNames.length; i++) { | |
| parameterInfo.append("\n").append(parameterNames[i]).append(':').append(args[i]); | |
| } | |
| // beginning of the method | |
| LOGGER.info("beginning of the method - " + className + "." + methodName + " - parameters:" + parameterInfo); | |
| final StopWatch stopWatch = new StopWatch(); | |
| // for calculating execution time | |
| stopWatch.start(); | |
| Object result = proceedingJoinPoint.proceed(); | |
| stopWatch.stop(); | |
| // end of method | |
| LOGGER.info( | |
| "end of method - " + className + "." + methodName + " :: " + stopWatch.getTotalTimeMillis() + " ms"); | |
| return result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment