SpringBoot 之SpringAOP 請求日誌記錄功能(支持POST和GET)

首先請參考:SpringBoot 之 SpringMVC攔截器從Request中獲取參數並解決request的請求流只能讀取一次的問題

參考完上面的代碼,現在開始編輯請求日誌記錄功能,核心功能代碼如下:

1、日誌註解標籤定義:

package com.digipower.erms.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SysLog {
	String value() default "";
	int type();
}

2、Spirng AOP 切面功能代碼:

package com.digipower.erms.aspect;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import com.alibaba.druid.util.StringUtils;
import com.digipower.erms.annotation.SysLog;
import com.digipower.erms.api.LogRecordService;
import com.digipower.erms.domain.LogRecord;
import com.digipower.erms.global.ErmsGlobal;
import com.digipower.erms.util.HttpContextUtils;
import com.digipower.erms.util.HttpUtils;
import com.digipower.erms.util.SecurityUtils;

@Aspect
@Component
public class SysLogAspect {
	public static final Logger log = LoggerFactory.getLogger(SysLogAspect.class);
	public static final List<String> filter =  Arrays.asList("request","response");

	
	@Autowired
	private LogRecordService service;
	
	@Autowired
	SecurityUtils securityUtils;
	
	@Pointcut("@annotation(com.digipower.erms.annotation.SysLog)")
    public void pointcut(){}
	
	@Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 執行方法
            result = point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 執行時長(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日誌
        save(point,time);
        return result;
    }

	private void save(ProceedingJoinPoint joinPoint, long time){
		LogRecord record = new LogRecord();

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String method = request.getMethod();
        String requestBody = null;
        if("post".equals(method)){
            SQLInjectionHttpServletRequestWrapper wrapper = new     
                                       SQLInjectionHttpServletRequestWrapper(request);
    		requestBody = wrapper.getRequestBodyParame();
        } else {
            Enumeration<String> names = request.getParameterNames(); 
    		// 請求參數轉換JSON 對象
			List<Map> container = new ArrayList<Map>();
			while(names.hasMoreElements()){
				Map<String,String> map = new HashMap<String,String>();
				String key = names.nextElement();
				String value = request.getParameter(key);
				map.put(key, value);
				container.add(map);
			}
			requestBody = JSON.toJSONString(container);
        }
		
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 註解對象獲取
        SysLog sysLog = method.getAnnotation(SysLog.class);
        if (sysLog != null) {
            // 註解上的描述
        	record.setLogType(Short.valueOf(""+sysLog.type()));
        	record.setLogDesc(sysLog.value());
        }
        // 請求類名和方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        record.setClassMethod(className + "." + methodName + "()");

        // 請求的方法參數名稱
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (paramNames != null) {
            record.setParames(params.toString());
            if(!StringUtils.isEmpty(requestBody )){
            	record.setParameValue(requestBody );
            }
        }
        // 請求地址
        HttpServletRequest request = HttpContextUtils.getRequest();
        String ip = HttpUtils.getIpAddress(request);
        record.setIpAddress(ip);
        
        // 操作用戶
       String username = securityUtils.getAuthUserPin(request);
       record.setUsername(username);
       
       // 創建時間
       record.setCreateTime(new Date()); 
       service.insert(record);
       
	}

}

3、 日誌實體對象:

package com.digipower.erms.domain;

import java.util.Date;

import com.digipower.erms.common.model.BaseModel;

public class LogRecord extends BaseModel {
    private Long sid;

    private Short logType;

    private String logDesc;

    private String classMethod;

    private String parames;

    private String username;

    private String ipAddress;

    private Date createTime;
    
    private String parameValue;

	public String getParameValue() {
		return parameValue;
	}

	public void setParameValue(String parameValue) {
		this.parameValue = parameValue;
	}

	public Long getSid() {
        return sid;
    }

    public void setSid(Long sid) {
        this.sid = sid;
    }

    public Short getLogType() {
        return logType;
    }

    public void setLogType(Short logType) {
        this.logType = logType;
    }

    public String getLogDesc() {
        return logDesc;
    }

    public void setLogDesc(String logDesc) {
        this.logDesc = logDesc == null ? null : logDesc.trim();
    }

    public String getClassMethod() {
        return classMethod;
    }

    public void setClassMethod(String classMethod) {
        this.classMethod = classMethod == null ? null : classMethod.trim();
    }

    public String getParames() {
        return parames;
    }

    public void setParames(String parames) {
        this.parames = parames == null ? null : parames.trim();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress == null ? null : ipAddress.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime == null ? null : createTime;
    }
}

springboot + mybatis 實現數據入庫:

springboot + springsecurity 工具類封裝:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章