[JAVA] Output system log by Spring AOP technology

What is Spring AOP?

In the Spring Framework, "AOP" is an important core technology along with DI (Dependency Injection). AOP stands for "Aspect Oriented Programming". Aspects are what are commonly referred to as "cross-cutting concerns."

environment

Spring AOP annotation term

1.@Aspect By attaching @Aspect to a class, that class will be recognized as Aspect. 2.@Pointcut Specify the location (method) to insert the cross-cutting process. 3.@Before Advice that is executed before processing the target method. 4.@After Advice that is always executed regardless of the processing result of the target method. 5.@AfterReturning Advice that is executed only when the processing of the target method is completed correctly. 6.@AfterThrowing Advice that is executed only when an exception occurs while processing the target method.

Implementation demo

LoggingAspect.java


package aspect.log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**Log output aspect class. */
@Aspect
@Component
public class LoggingAspect {

  private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

  /**Public method pointcut.System error log output*/
  @Pointcut("execution(public * *(..))")
  private void publicLog() {}

  /**dao package pointcut.db operation log output*/
  @Pointcut("within(app.dao..*)")
  private void dbLog() {}

  /**Web package pointcut.Log output of requests, responses, etc.*/
  @Pointcut("within(app.web..*)")
  private void webLog() {}

  /**
   *Log output before method execution.
   *
   * @param jp join point
   */
  @Before("publicLog() && (dbLog() || webLog())")
  public void dobefore(JoinPoint jp) {

    Signature sig = jp.getSignature();
    String args = "None";
    if(jp.getArgs() != null && jp.getArgs().length > 0 ) {
    	args = Arrays.toString(jp.getArgs());
    }
    logger.info("[Start operation]" +"Method:"+sig.getDeclaringTypeName() + "."+sig.getName()+"#Input parameters:"+ args);
  }

  /**
   *Log output after method execution.
   *
   * @param jp join point
   */
  @AfterReturning(pointcut="publicLog() && (dbLog() || webLog())",returning="returnValue")
  public void doAfterReturning(JoinPoint jp,Object returnValue) {
    Signature sig = jp.getSignature();
    logger.info("[End of operation]"+"Method:"+sig.getDeclaringTypeName() + "."+sig.getName()+"#Return value:" + returnValue);
  }

  /**
   *If an error occurs, log output.
   *
   * @param jp join point
   */
  @AfterThrowing (pointcut="publicLog() && (dbLog() || webLog())",throwing="ex")
  public void doAfterThrowing(JoinPoint jp,Exception ex) {
	  Signature sig = jp.getSignature();
	  StringWriter erMessage=new StringWriter();
	  ex.printStackTrace(new PrintWriter(erMessage));
	  logger.info("【error】" + "Method:"+sig.getDeclaringTypeName() + "."+sig.getName()+"#Error message:" + erMessage.toString());

  }
}

Finally

Thank you for reading to the end.

reference: https://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/core.html#aop https://iikanji.hatenablog.jp/entry/2018/04/26/204324

Recommended Posts

Output system log by Spring AOP technology
Spring Data JPA SQL log output
Output Spring Boot log in json format
Output request and response log in Spring Boot
About Spring AOP
About spring AOP
Request parameter log output sample Java & Spring MVC
Sample code for log output by Java + SLF4J + Logback
About Java log output
About Spring AOP Pointcut
Overview of Spring AOP
Output embedded Tomcat access log to standard output with Spring Boot