add AOP for logging

This commit is contained in:
0samsung0 2025-05-20 18:40:35 +03:00
parent 8393b074fc
commit 0a43a7a311

View file

@ -1,27 +1,34 @@
package org.springframework.samples.petclinic;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
//Pointcut: all methods in package "model"
@Before("execution(* model.BaseEntity.getId())")
public void logBeforeMethod(){
System.out.println("model.BaseEntity.getId...");
}
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Before("execution(* model.NamedEntity.getName())")
public void logBeforeMethod2(){
System.out.println("model.NamedEntity.getName...");
}
@Around("execution(* org.springframework.samples.petclinic..*.*(..))")
public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
@Before("execution(* model.Person.*())")
public void logBeforeMethod3(){
System.out.println("model.Person*");
logger.info("Начало выполнения метода: {}.{}", className, methodName);
long startTime = System.currentTimeMillis();
Object result = null;
try {
result = joinPoint.proceed();
return result;
} finally {
long endTime = System.currentTimeMillis();
logger.info("Завершение выполнения метода: {}.{} (время выполнения: {} мс)",
className, methodName, (endTime - startTime));
}
}
}