🧶

SpringBootの横断的なログ出力

2022/01/04に公開

前回の続き
https://zenn.dev/marumarumeruru/articles/0d1b86afff0b11

com.example.demo.component配下のクラスのメソッドに対して、開始と終了でログを出力する
既存のクラスを変更することなく、ログを出力できる

build.gradle dependenciesに追加
	implementation 'org.springframework.boot:spring-boot-starter-aop'
AppLog.java
package com.example.demo.aspect;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AppLog {
  private final Logger log;

  public AppLog(){
      super();
      log = LoggerFactory.getLogger(AppLog.class);
  }

  @Before("within(com.example.demo.component.*..*)")
  public void beforeLog(JoinPoint joinpoint){
      log.info("START: " + joinpoint.getSignature());
  }

  @After("within(com.example.demo.component.*..*)")
  public void afterLog(JoinPoint joinpoint){
      log.info("END: " + joinpoint.getSignature());
  }
}

PointCut式で範囲を指定している

ログ
2022-01-04 23:12:14.967  INFO 49149 --- [nio-8080-exec-2] com.example.demo.aspect.AppLog           : START: User com.example.demo.component.user.UserController.getUser(Integer)
2022-01-04 23:12:14.967  INFO 49149 --- [nio-8080-exec-2] c.e.demo.component.user.UserController   : getUser
2022-01-04 23:12:14.967  INFO 49149 --- [nio-8080-exec-2] com.example.demo.aspect.AppLog           : START: User com.example.demo.component.user.UserService.findById(User)
2022-01-04 23:12:15.002  INFO 49149 --- [nio-8080-exec-2] com.example.demo.aspect.AppLog           : END: User com.example.demo.component.user.UserService.findById(User)
2022-01-04 23:12:15.002  INFO 49149 --- [nio-8080-exec-2] com.example.demo.aspect.AppLog           : END: User com.example.demo.component.user.UserController.getUser(Integer)

Discussion