欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring AOP 日志记录

程序员文章站 2022-04-25 20:22:53
...
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());
	}
    
}