Spring AOP 로그 기록

2719 단어 자바
package com.config;
import java.util.Date;

/**
 * AOP       
 */
import org.aspectj.lang.JoinPoint;
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.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.bean.InfoLogBean;
import com.service.LogService;
import com.util.DateUtil;

@Aspect
@Component
public class WebLogAspect {
	
	@Autowired
	private LogService logService;
	
	//     
	private String startTime;
        //    
	private String endtime;
	
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    
    @Before(value="execution(public * com.controller..*.*(..))") 
    public void doBefore(JoinPoint joinPoint) {
    	startTime = DateUtil.getDateTimeHelper(new Date());
    }
    
    /**
     *       
     * @param joinPoint
     * @param result
     */
    @AfterReturning(returning = "result", value="execution(public * com.controller..*.*(..))") 
    public void afterReturnMethod(JoinPoint joinPoint,Object result) { 
    	endtime = DateUtil.getDateTimeHelper(new Date());
    	String code=joinPoint.getSignature().getName();
    	String req=JSON.toJSONString(joinPoint.getArgs());
    	String resp=JSON.toJSONString(result);
    	InfoLogBean lb=new InfoLogBean();
    	lb.setAddName(code);
    	lb.setReqJson(req);
    	lb.setRespJson(resp);
    	lb.setExpError("0");
    	lb.setStatusCD("0");
    	lb.setCreateDate(startTime);
    	lb.setEndDate(endtime);
        logService.addLog(lb);
    }
    
    /**
     *       
     * @param joinPoint
     * @param ex
     */
	@AfterThrowing(value = "execution(public * com.controller..*.*(..))", throwing = "ex")
	public void afterThrowing(JoinPoint joinPoint, Exception ex) {
		endtime = DateUtil.getDateTimeHelper(new Date());
		String code = joinPoint.getSignature().getName();
		String req = JSON.toJSONString(joinPoint.getArgs());
		String resp = JSON.toJSONString("'excause:'"+ ex.toString() + ";  exMessage:" + ex.getMessage());
		InfoLogBean lb = new InfoLogBean();
		lb.setAddName(code);
		lb.setReqJson(req);
		lb.setRespJson(resp);
		lb.setRespJson(resp);
		lb.setExpError("1");
		lb.setStatusCD("1");
		lb.setCreateDate(startTime);
    	lb.setEndDate(endtime);
		logService.addLog(lb);
		logger.error("AOP:WebLogAspect.afterThrowing method, error message:"+ ex.toString());
	}
    
}

 
 

좋은 웹페이지 즐겨찾기