创建切面类记录访问日志

1、添加依赖


    1.2.47



    
		com.alibaba
		fastjson
		${fastjson.version}
	
    
		org.springframework.boot
		spring-boot-starter-aop
	

2、创建切面类

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.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.richfit.common.utils.HttpContextUtils;
import com.richfit.common.utils.IpUtils2;

@Aspect
@Component
public class OperationLogAspect {

	private Logger logger = LoggerFactory.getLogger(getClass());

	// pointcut1 配置的是对xxx模块下的所有controller访问做日志记录
	private final String pointcut1 = "execution(* com.xxx.modules.xxx.controller..*.*(..))";
	// pointcut2 配置的是对系统登录login方法访问做日志记录
	private final String pointcut2 = "execution(* com.xxx.modules.sys.controller.SysLoginController.login(..))";

	// 切点
	@Pointcut(value = pointcut1)
	public void log1() {
	}

	@Pointcut(value = pointcut2)
	public void log2() {
	}

	@Around(value = "log1() || log2()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		String ipAddr = IpUtils2.getIpAddr(request); // 获取ip地址,如192.168.152.152
		int port = request.getServerPort(); // 获取端口号
		StringBuffer url = request.getRequestURL(); // 获取请求的完整路径
		String method = request.getMethod(); // 获取请求的方式(POST/GET等)
		String protocol = request.getProtocol(); // 获取协议及版本号

		Object result = null;
		StringBuilder sbLog = new StringBuilder("\n");
		try {
			sbLog.append(String.format("IP地址:%s\r\n", ipAddr));
			sbLog.append(String.format("端口:%s\r\n", port));
			sbLog.append(String.format("请求路径:%s\r\n", url));
			sbLog.append(String.format("请求方式:%s\r\n", method));
			sbLog.append(String.format("协议:%s\r\n", protocol));

			sbLog.append(String.format("类名:%s\r\n", proceedingJoinPoint.getTarget().getClass().getName()));
			MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
			sbLog.append(String.format("方法:%s\r\n", methodSignature.getMethod().getName()));

			Object[] args = proceedingJoinPoint.getArgs();
			for (Object o : args) {
				sbLog.append(String.format("参数:%s\r\n", JSON.toJSON(o)));
			}

			long startTime = System.currentTimeMillis();
			result = proceedingJoinPoint.proceed();
			long endTime = System.currentTimeMillis();
			sbLog.append(String.format("返回:%s\r\n", JSON.toJSON(result)));
			sbLog.append(String.format("耗时:%ss", endTime - startTime));
		} catch (Exception ex) {
			sbLog.append(String.format("异常:%s", ex.getMessage()));
		} finally {
			logger.info(sbLog.toString());
		}
		return result;
	}
}

 

你可能感兴趣的:(日志)