1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AOPのロギングのクラス名を各AOP対象のクラス名にする

Posted at

色々考えたが難しかった

  • 事前にBeanに"Logger"を付加したロガーを作って登録しておこうかと思ったが、調べるのに時間が掛かりそう。
  • PostBeanProcessorにて、Beanは作れない。

今の所の実装

  1. AOP時にBean名+"Logger"のロガーをmapにキャッシュ。
  2. 二回目以降、これを使う

package com.example.aop;

import lombok.AllArgsConstructor;
import org.aspectj.lang.JoinPoint;
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.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@AllArgsConstructor
public class MethodStartEndAspect {
    private final Map<String, Logger> map = new HashMap<>();

    @Before("execution(* com.example..*(..))")
    public void start(JoinPoint joinPoint) {
        String loggerName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        Logger logger;
        if (map.containsKey(loggerName)) {
            logger = map.get(loggerName);
        } else {
            logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringType().getSimpleName());
            map.put(loggerName, logger);
        }

        logger.info("START {}#{}", joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName());
    }

    @After("execution(* com.example..*(..))")
    public void end(JoinPoint joinPoint) {
        String loggerName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        Logger logger = map.get(loggerName);
        logger.info("END {}#{}", joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName());
    }

}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?