@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented
public @interface OperLog {
String operModul() default ""; // 操作模块
OperLogTypeEnum operType(); // 操作类型
String operDesc() default ""; // 操作说明
}
标签:String,ip,request,lubansoft,AOP,import,日志,com From: https://www.cnblogs.com/Acaak/p/17377432.html
package com.lubansoft.meter.highway.controller.common.interceptor;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.lubansoft.meter.highway.common.util.Constant;
import com.lubansoft.meter.highway.common.util.CustomLogger;
import com.lubansoft.meter.highway.service.sevice.OpLogService;
import com.lubansoft.meter.highway.service.sevice.model.OpLogDTO;
import com.lubansoft.meter.highway.service.sevice.ExcLogService;
import com.lubansoft.meter.highway.service.sevice.constant.SystemTypeEnum;
import com.lubansoft.meter.highway.service.sevice.model.ExcLogDTO;
import com.lubansoft.platform.zk.token.bean.TokenValue;
import com.lubansoft.platform.zk.token.common.TokenContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
public class OperLogAspect implements Ordered {
private ThreadLocal<Long> execTimeThreadLocal = new ThreadLocal<>();
@Autowired
private OpLogService opLogService;
@Autowired
private ExcLogService excLogService;
@Override
public int getOrder() {
return 0;
}
/**
* 设置操作日志切入点 记录操作日志 在注解的位置切入代码
*/
@Pointcut("@annotation(com.lubansoft.meter.highway.controller.common.interceptor.OperLog)")
public void operLogPointCut() {
}
/**
* 设置操作异常切入点 记录异常日志 扫描所有controller包下操作
*/
@Pointcut("execution(* com.lubansoft.meter.highway.controller.controller.*.*(..)) || "
+ "execution(* com.lubansoft.meter.highway.controller.controller.center.*.*(..))")
public void operExceptionLogPoinCut() {
}
@Before("operLogPointCut()")
public void doOperLogPointCutBefore() {
execTimeThreadLocal.set(System.currentTimeMillis());
}
@After("operLogPointCut()")
public void doOperLogPointCutAfter() {
execTimeThreadLocal.set(System.currentTimeMillis() - execTimeThreadLocal.get());
}
/**
*
* @param joinPoint
* @param keys
*/
@AfterReturning(value = "operLogPointCut()", returning = "keys")
public void saveOperLog(JoinPoint joinPoint, Object keys) {
// 获取RequestAttributes
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// 从获取RequestAttributes中获取HttpServletRequest的信息
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
// 从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取切入点所在的方法
Method method = signature.getMethod();
// 获取操作
OperLog opLog = method.getAnnotation(OperLog.class);
if (opLog == null) { return; }
String operModul = opLog.operModul();
OperLogTypeEnum operType = opLog.operType();
String operDesc = opLog.operDesc();
if (OperLogTypeEnum.BASIC_QUERY.equals(operType)) {
return;
}
String userId = (String) request.getAttribute(Constant.USERID_SESSION_KEY);
String uri = request.getRequestURI().replace(request.getContextPath(), "");
String ip = getIpAddress(request);
// 获取请求的类名
String className = joinPoint.getTarget().getClass().getName();
// 获取请求的方法名
String methodName = className + "." + method.getName();
// 请求的参数
String requestMethod = request.getMethod();
Map<String, String> rtnMap = new HashMap<>();
String reqParams = "";
if("GET".equals(requestMethod)) {
rtnMap = converMap(request.getParameterMap());
reqParams = JSON.toJSONString(rtnMap);
}
if("POST".equals(requestMethod)) {
if(null != joinPoint.getArgs() && 2 < joinPoint.getArgs().length) {
reqParams = JSONUtil.toJsonStr(joinPoint.getArgs()[2]);
}
}
if(!StringUtils.isEmpty(reqParams) && reqParams.length() > 1000){
reqParams = reqParams.substring(0, 1000);
}
String respContent = JSON.toJSONString(keys);
String opVersion = "";
Long time = execTimeThreadLocal.get();
TokenValue tokenValue = TokenContextHolder.get();
String username = null != tokenValue ? tokenValue.getUsername() : "";
OpLogDTO opLogDTO = new OpLogDTO(null, userId, username, operModul, operType.getValue(), operDesc,
methodName, uri, reqParams, respContent, time, ip, opVersion);
opLogDTO.setType(SystemTypeEnum.FRONT.getType());
try {
opLogService.insertOpLog(opLogDTO);
} catch (Exception e) {
CustomLogger.getLogger().error("操作日志记录失败:" + e.getMessage());
}
}
/**
* 异常通知 用于拦截service层记录异常日志
*
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
// 获取RequestAttributes
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(requestAttributes == null) {
return;
}
// 从获取RequestAttributes中获取HttpServletRequest的信息
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
// 从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取切入点所在的方法
Method method = signature.getMethod();
// 获取操作
OperLog opLog = method.getAnnotation(OperLog.class);
if (opLog == null) { return; }
String operModul = opLog.operModul();
OperLogTypeEnum operType = opLog.operType();
Long userId = (Long) request.getAttribute(Constant.USERID_SESSION_KEY);
String uri = request.getRequestURI().replace(request.getContextPath(), "");
String ip = getIpAddress(request);
// 获取请求的类名
String className = joinPoint.getTarget().getClass().getName();
// 获取请求的方法名
String methodName = className + "." + method.getName();
// 请求的参数
Map<String, String> rtnMap = converMap(request.getParameterMap());
// 将参数所在的数组转换成json
String params = JSON.toJSONString(rtnMap);
String opVersion = "";
String excDesc = stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace());
if(excDesc.length() > 1000){
excDesc = excDesc.substring(0, 1000);
}
ExcLogDTO excLogDTO = new ExcLogDTO(null, userId, "", operModul, operType.getValue(), e.getClass().getName(),
excDesc, methodName, uri, params, ip, opVersion);
excLogDTO.setType(SystemTypeEnum.FRONT.getType());
try {
excLogService.insertExcLog(excLogDTO);
} catch (Exception e1) {
CustomLogger.getLogger().error("异常日志记录失败:" + e1.getMessage());
}
}
private Map<String, String> converMap(Map<String, String[]> paramMap) {
Map<String, String> rtnMap = new HashMap<String, String>();
for (String key : paramMap.keySet()) {
rtnMap.put(key, paramMap.get(key)[0]);
}
return rtnMap;
}
/**
* 获取请求的IP地址
*
* @param request
* @return
*/
public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 转换异常信息为字符串
*
* @param exceptionName 异常名称
* @param exceptionMessage 异常信息
* @param elements 堆栈信息
*/
public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
StringBuffer strbuff = new StringBuffer();
for (StackTraceElement stet : elements) {
strbuff.append(stet + "\n");
}
String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
return message;
}
}