To create a custom annotation for aspect-oriented logging in Java using Spring's AOP, you'll first need to define the annotation, then an aspect that uses this annotation to log the method inputs and outputs.
Below is an example implementation using Spring AOP:
- Define a custom annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
}
- Create an aspect to handle the custom annotation:
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
// Define the pointcut for methods annotated with @Loggable
@Pointcut("@annotation(Loggable)")
public void loggableMethods() {}
// Around advice to log method inputs and outputs
@Around("loggableMethods()")
public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
// Get method input arguments
Object[] args = joinPoint.getArgs();
String argsStr = buildArgumentsString(signature.getParameterNames(), args);
// Log method entry with input arguments
logger.info("Entering method: {} with args: {}", methodName, argsStr);
try {
// Proceed with the method execution
Object result = joinPoint.proceed();
// Log method exit with result
logger.info("Exiting method: {} with result: {}", methodName, result);
return result;
} catch (Exception ex) {
// Log exceptions if any
logger.error("Exception in method: {} with args: {}", methodName, argsStr, ex);
throw ex;
}
}
private String buildArgumentsString(String[] paramNames, Object[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
sb.append(paramNames[i]).append("=").append(args[i]);
if (i < args.length - 1) {
sb.append(", ");
}
}
return sb.toString();
}
}
- Use the custom
@Loggable annotation on a method:
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Loggable
public int add(int a, int b) {
return a + b;
}
}
In the code above:
- The
@Loggable annotation is the marker you can put on methods you want to log.
- The
LoggingAspect class defines an "around" advice that logs information before and after the annotated method executes.
- The
logMethodExecution method constructs logs with method names and their input/output parameters.
Remember to have Spring AOP dependencies included in your project and aspectjweaver as well for the aspect to work. Also, make sure you have enabled AspectJ’s annotation processing with @EnableAspectJAutoProxy in your configuration.