LogAspect.java 5.35 KB
package com.glsx.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.glsx.common.annotation.Log;
import com.glsx.common.constants.ResultObject;
import com.glsx.common.feign.client.OperateLogClient;
import com.glsx.common.pojo.OperateLog;
import com.glsx.common.utils.UserUtils;

/**
 * 
 * @Title WebRequestLogAspect.java
 * @Package com.glsx.common.aspect
 * @Description TODO 操作日志
 * @author zhanghj
 * @date 2019年2月2日 下午2:52:49
 * @version 1.0.0
 */

@Component
@Aspect
public class LogAspect {

	@Autowired
	private OperateLogClient operateLogClient;
	
	private static Logger logger = LoggerFactory
			.getLogger(LogAspect.class);

	private ThreadLocal<OperateLog> tlocal = new ThreadLocal<OperateLog>();

	/**
	 * 配置织入点
	 */
	@Pointcut("@annotation(com.glsx.common.annotation.Log)")
	public void webRequestLog() {
	}

	@Before("webRequestLog()")
	public void doBefore(JoinPoint joinPoint) {
		try {
			// 获得注解
			Log log = getAnnotationLog(joinPoint);
			if (log == null) {
				return;
			}


			// 接收到请求,记录请求内容
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest request = attributes.getRequest();
			String beanName = joinPoint.getSignature().getDeclaringTypeName();
			String uri = request.getRequestURI();
			String methodName = joinPoint.getSignature().getName();
			methodName = beanName + methodName;
			String ip = getIpAddr(request);
			/*String method = request.getMethod();
			String params = "";
			if ("POST".equals(method)) {
				Object[] paramsArray = joinPoint.getArgs();
				params = argsArrayToString(paramsArray);
			} else {
				Map<?, ?> paramsMap = (Map<?, ?>) request
						.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
				if (null != paramsMap) {
					params = paramsMap.toString();
				}
			}*/

			OperateLog optLog = new OperateLog();
			optLog.setCreateTime(new Date());
			String operateType = log.operateType();
			String menuName = log.menuName();
			optLog.setMenuName(menuName);
			optLog.setOperateType(operateType);
			optLog.setUri(uri);
			optLog.setIp(ip);
			tlocal.set(optLog);

		} catch (Exception e) {
			logger.error("***操作请求日志记录失败doBefore()***", e);
		}
	}

	@AfterReturning(returning = "result", pointcut = "webRequestLog()")
	public void doAfterReturning(Object result) {
		try {
			ResultObject res = (ResultObject) result;
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest request = attributes.getRequest();
			
			// 处理完请求,返回内容
			OperateLog optLog = tlocal.get();
			Integer userId = UserUtils.getUserId(request);
			optLog.setCreateBy(userId);
			optLog.setOperateStatus(res.getCode());
			optLog.setRemark(res.getMessage());
			logger.debug("uri=" + optLog.getUri() + "; methodName="
					+ optLog.getMethodName() + "; ip=" + optLog.getIp()
					+ "; createBy=" + optLog.getCreateBy() + "; params="
					+ optLog.getParams());

			operateLogClient.save(optLog);
		} catch (Exception e) {
			logger.error("***操作请求日志记录失败doAfterReturning()***", e);
		}
	}

	/**
	 * 获取登录用户远程主机ip地址
	 * 
	 * @param request
	 * @return
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 请求参数拼装
	 * 
	 * @param paramsArray
	 * @return
	 */
	private String argsArrayToString(Object[] paramsArray) {
		String params = "";
		if (paramsArray != null && paramsArray.length > 0) {
			for (int i = 0; i < paramsArray.length; i++) {
				Object jsonObj = JSON.toJSON(paramsArray[i]);
				params += jsonObj.toString() + " ";
			}
		}
		return params.trim();
	}

	/**
	 * 是否存在注解,如果存在就获取
	 */
	private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(Log.class);
		}
		return null;
	}

}