1. 程式人生 > >spring aop記錄日誌

spring aop記錄日誌

spring aop記錄日誌

		<dependency>
		    <groupId>javassist</groupId>
		    <artifactId>javassist</artifactId>
		    <version>3.12.1.GA</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.8</version>
		</dependency>
package com.try2better.daily.component;

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

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

@Retention(RetentionPolicy.RUNTIME)  
@Target({ElementType.METHOD,ElementType.TYPE})  
@Documented
//最高優先級  
@Order(Ordered.HIGHEST_PRECEDENCE)  
public @interface Try2betterAspectLog {
	String name() default "";  
}
package com.try2better.daily.component;

import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.try2better.daily.entity.LogRecordEntity;
import com.try2better.daily.util.LoggerUtil;


@Aspect
@Component
public class LogAspect {
	
    @AfterReturning(returning="result", pointcut="@annotation(com.try2better.daily.component.Try2betterAspectLog)")
    public void after(JoinPoint joinPoint,Object result) throws ClassNotFoundException{
    	Object target = joinPoint.getTarget();
    	if(target == null || !(target instanceof BaseController)){
    		throw new RuntimeException("此controller沒有繼承BaseController!");
    	}
    	BaseController controller = (BaseController)joinPoint.getTarget();
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    	String uri = request.getRequestURI();
    	String url = request.getRequestURL().toString();
    	String queryString = request.getQueryString();
    	String classType = joinPoint.getTarget().getClass().getName();    
        Class<?> clazz = Class.forName(classType);    
        String className = clazz.getName();    
        String methodName = joinPoint.getSignature().getName(); //獲取方法名稱   
    	 //獲取參數名稱和值  
        Map<String,Object> parameterMap = getFieldsNameValueMap(joinPoint); 
        
        LogRecordEntity logRecordEntity = new LogRecordEntity();
        logRecordEntity.setUrl(url);;
        logRecordEntity.setUri(uri);;
        logRecordEntity.setQueryString(queryString);;
    	
        logRecordEntity.setUserId("admin");;
        logRecordEntity.setRequestDate(new java.util.Date());;
    	
        logRecordEntity.setClassName(className);;
        logRecordEntity.setMethodName(methodName);;
        logRecordEntity.setParameterMap(parameterMap);;
        logRecordEntity.setResult(result);;
    	
	LoggerUtil.info(controller.getLogger(), logRecordEntity);
    }
  
    
    
    private Map<String,Object> getFieldsNameValueMap(JoinPoint joinPoint){  
    	Map<String,Object > map=new HashMap<String,Object>();  
    	try {
    		Object[] args = joinPoint.getArgs();
        	String classType = joinPoint.getTarget().getClass().getName();    
            Class<?> clazz = Class.forName(classType);    
            String clazzName = clazz.getName();    
            String methodName = joinPoint.getSignature().getName(); //獲取方法名稱   
           
            ClassPool pool = ClassPool.getDefault();    
            ClassClassPath classPath = new ClassClassPath(this.getClass());    
            pool.insertClassPath(classPath);    
            CtClass cc = pool.get(clazzName);    
            CtMethod cm = cc.getDeclaredMethod(methodName);    
            javassist.bytecode.MethodInfo methodInfo = cm.getMethodInfo();  
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();    
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);    
            if (attr == null) {    
                throw new RuntimeException();
            }    
            int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;    
            for (int i = 0; i < cm.getParameterTypes().length; i++){    
                map.put( attr.variableName(i + pos),args[i]);//paramNames即參數名    
            }    
		} catch (Exception e) {
			e.printStackTrace();
		}
        return map;    
    }    
}
package com.try2better.daily.entity;

import java.util.Date;
import java.util.Map;

public class LogRecordEntity {

	private String url;
	private String uri;
	private String queryString;
	
	private String userId;
	private Date requestDate;
	
	private String className;
	private String methodName;
	private Map<String,Object> parameterMap;
	private Object result;
	
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getUri() {
		return uri;
	}
	public void setUri(String uri) {
		this.uri = uri;
	}
	public String getQueryString() {
		return queryString;
	}
	public void setQueryString(String queryString) {
		this.queryString = queryString;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public Date getRequestDate() {
		return requestDate;
	}
	public void setRequestDate(Date requestDate) {
		this.requestDate = requestDate;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getMethodName() {
		return methodName;
	}
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}
	public Map<String, Object> getParameterMap() {
		return parameterMap;
	}
	public void setParameterMap(Map<String, Object> parameterMap) {
		this.parameterMap = parameterMap;
	}
	public Object getResult() {
		return result;
	}
	public void setResult(Object result) {
		this.result = result;
	}
	
	
}
package com.try2better.daily.util;

import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.try2better.daily.entity.LogRecordEntity;

public class LoggerUtil {

	public static void info(Logger logger,LogRecordEntity logRecordEntity){
		logger.info(JSONObject.toJSONString(logRecordEntity));
	}
}
package com.try2better.daily.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.try2better.daily.component.BaseController;
import com.try2better.daily.component.Try2betterAspectLog;
import com.try2better.daily.entity.Task;
import com.try2better.daily.util.qrcode.EncodeRequestEntity;
import com.try2better.daily.util.qrcode.EncodeResultEntity;
import com.try2better.daily.util.qrcode.QRCodeHelper;

@Controller
@RequestMapping("/")
public class QRCodeController extends BaseController{

	
	@Try2betterAspectLog
	@ResponseBody
	@RequestMapping("/method")
	public Map<String,Object> method1(String a,Integer b){
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("1", "1");
		return map;
	}
	
}
package com.try2better.daily.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaseController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	public Logger getLogger() {
		return logger;
	}
	
}


spring aop記錄日誌