Java切面拦截请求并记录日志
-
使用@Aspect注解标记类;
-
创建拦截标识——创建一个注解;
-
使用拦截标识制作切点;
-
创建拦截及处理机制,例如请求开始前,结果返回后,异常出错后,需要配合使用各种状态的注解;
-
以上,完成切面日志拦截。
-
使用是,在控制层(controller层)需要被拦截的方法上加自己创建的注解就可以了。
-
还有一种拦截方式,可以通配式拦截,例如拦截所有以update字样开头的方法,但这种方式需要代码定义的时候高度规范。
- 创建拦截标识--注解
/**
* @author darly
* @version 2019年10月30日 上午10:57:36
* @declare LogRecord.java
* 日志记录注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface LogRecord {
String operation() default "";
}
- 创建拦截处理器
package cc.julong.soft.modules.sys.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* 日志工具类
* @author ThinkGem
* @version 2014-11-7
*/
@Aspect
@Component
public class LogUtils {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
@Pointcut("@annotation(cc.julong.soft.framework.annotation.LogRecord)")
public void controllerAspect() {};
@Before("controllerAspect()")
public void boBefore(JoinPoint joinPoint) {
threadLocal.set(System.currentTimeMillis());
}
@AfterReturning(value = "controllerAspect()", returning = "res")
public void userLogRecord(JoinPoint point, Object res) {
saveLog(Servlets.getRequest(), res, null, null);
}
@AfterThrowing(value="controllerAspect()", throwing = "throwing")
public void error(Throwable throwing) {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
//将报错信息写入error字段
saveLog(Servlets.getRequest(), throwing.getMessage(), throwing.getMessage(), null);
throwing.printStackTrace(new PrintStream(byteArrayOutputStream));
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用切点进行拦截
/**
* @param model
* @throws IOException
*/
@LogRecord
@ResponseBody
@RequestMapping(value = "addUpload")
public Result addUpload(@RequestParam(value = "file") MultipartFile multipartFile,
HttpServletRequest request, HttpServletResponse response) throws IOException {
}