develog

Spring AOP LoggingAdvice 본문

Dev/Spring

Spring AOP LoggingAdvice

냐옴 2013. 11. 29. 19:35

import java.util.List;


import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.Signature;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;



public class LoggingAdvice {

    

    private Log logger = LogFactory.getLog(getClass());

    

    public void before(JoinPoint joinPoint) {

        if (!logger.isDebugEnabled()) return;

        

        StringBuffer sb = new StringBuffer();

        sb.append(getMethodNm(joinPoint));

        sb.append(" (before)");

        sb.append(getArgs(joinPoint));

        

        logger.debug(sb.toString());

    }

    

    public void afterReturning(JoinPoint joinPoint, Object retVal) {

        if (!logger.isDebugEnabled()) return;

        

        StringBuffer sb = new StringBuffer();

        sb.append(getMethodNm(joinPoint));

        sb.append(" (afterReturning)");

        

        if (retVal instanceof List) {

            List list = (List) retVal;

            if (list == null) {

                sb.append("\n" + "    " + "LIST, " + "null");

            } else {

                sb.append("\n" + "    " + "LIST, " + list.size() + " 건");

            }

        } else {

            sb.append("\n" + "    " + retVal);

        }

        

        logger.debug(sb.toString());

    }

    

    private String getMethodNm(JoinPoint joinPoint) {

        Signature signature = joinPoint.getSignature();

        StringBuffer sb = new StringBuffer();

        sb.append(signature.getDeclaringTypeName());

        sb.append(".");

        sb.append(signature.getName());

        return sb.toString();

    }

    

    private String getArgs(JoinPoint joinPoint) {

        StringBuffer sb = new StringBuffer();

        Object[] args = joinPoint.getArgs();

        for (int i = 0; i < args.length; i++) {

            Object object = args[i];

            if (object instanceof List) {

                sb.append("\n" + "    " + i + ". ");

                List list = (List) object;

                if (list == null) continue;

                for (int j = 0; j < list.size(); j++) {

                    sb.append("\n" + "       " + j + ". " + list.get(j));

                }

            } else {

                sb.append("\n" + "    " + i + ". " + object);

            }

        }

        return sb.toString();

    }

    

}



'Dev > Spring' 카테고리의 다른 글

Spring AOP Pointcut expression  (0) 2013.12.11
Spring AOP 설정  (0) 2013.12.11
REQUIRED, REQUIRES_NEW  (0) 2013.07.18
spring jar download  (0) 2013.07.09
Spring AOP Aspect 설정  (0) 2013.04.22
Comments