1、日志注解类
/**
* 系统日志注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
}
2、操作日志记录
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.annotation.SysLog;
import com.common.enums.BusinessStatus;
import com.common.lang.StringUtils;
import com.common.util.IpUtil;
import com.core.ipseek.IPLocation;
import com.core.ipseek.IPSeeker;
import com.core.web.CmsUtils;
import com.core.web.ServletUtils;
import com.coupon.entity.MerchantUser;
import com.coupon.entity.SysOperLog;
import com.coupon.manage.SysOperLogService;
/**
* 操作日志记录
*
*
* @Aspect:作用是把当前类标识为一个切面供容器读取
* @Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
* @Around:环绕增强,相当于MethodInterceptor
* @AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
* @Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
* @AfterThrowing:异常抛出增强,相当于ThrowsAdvice
* @After: final增强,不管是抛出异常或者正常退出都会执行
*
* 注意点:spring和springMVC是两个不同的容器,因为controller是springMVC容器加载的,而service是spring容器加载的,是无法互通的,所以AOP未生效。
* 若在controller中需要在 springmvc.xml文件进行注入
*/
@Aspect
@Component
public class SysLogAspect {
private static final Logger log = LoggerFactory.getLogger(SysLogAspect.class);
@Autowired
private SysOperLogService sysOperLogService;
@Autowired
private IPSeeker iPSeeker;
//日志切入点
@Pointcut("@annotation(com.common.annotation.SysLog)")
public void logPointCut() {
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
// @Around("logPointCut()")
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void around(JoinPoint joinPoint, Object jsonResult) {
handleLog(joinPoint, null,jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
// 获得注解
SysLog controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
HttpServletRequest request = ServletUtils.getRequest();
MerchantUser merchantUser = CmsUtils.getMerchantUser(request);
// *========数据库日志=========*//
SysOperLog operLog = new SysOperLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 请求的地址
String ip = IpUtil.getIPAddress(request);
IPLocation ipLocation = iPSeeker.getIPLocation(ip);
if(ipLocation!=null) {
operLog.setOperLocation(ipLocation.getArea());
}
operLog.setOperIp(ip);
operLog.setOperUrl(request.getRequestURI());
if (merchantUser != null) {
operLog.setOperName(merchantUser.getUserName());
operLog.setShopId(merchantUser.getShopId());
}
if (e != null) {
operLog.setStatus(BusinessStatus.FAIL.ordinal());
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(request.getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog);
operLog.setOperTime(new Date());
if(jsonResult!=null) {
String jsonString = JSON.toJSONString(jsonResult);
JSONObject jsonDate = JSONObject.parseObject(jsonString);
if(jsonDate.containsKey("title") && StringUtils.isNotBlank(jsonDate.getString("title"))) {
operLog.setTitle(jsonDate.getString("title"));
}
// 返回参数
operLog.setJsonResult(jsonString);
}
sysOperLogService.save(operLog);
} catch (Exception exp) {
// 记录本地异常日志
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param operLog 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, SysLog log, SysOperLog operLog) throws Exception {
// 设置action动作
operLog.setBusinessType(log.businessType().ordinal());
// 设置标题
operLog.setTitle(log.title());
// 设置操作人类别
operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request,参数和值
if (log.isSaveRequestData()) {
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog);
}
}
/**
* 获取请求的参数,放到log中
*
* @param operLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
String requestMethod = operLog.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
} else {
Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
}
}
/**
* 是否存在注解,如果存在就获取
*/
private SysLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(SysLog.class);
}
return null;
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (int i = 0; i < paramsArray.length; i++) {
if (paramsArray[i]!=null && !isFilterObject(paramsArray[i])) {
try {
params += JSON.toJSONString(paramsArray[i]) + " ";
} catch (Exception e) {
e.printStackTrace();
params += "";
}
}
}
}
return params.trim();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Iterator iter = collection.iterator(); iter.hasNext();) {
return iter.next() instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
}
}
参考项目:https://gitee.com/y_project/RuoYi-Vue 中有日志实现
3、xml配置
<!-- aop 日志记录 -->
<bean id="sysLogAspect" class="com.aspect.SysLogAspect"/>
<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
4、注解使用
@SysLog(title = "用户新增", businessType = BusinessType.INSERT)
@RequestMapping(value = "/o_save.do", method = RequestMethod.POST)
@ResponseBody
public ApiResult save(HttpServletRequest request, HttpServletResponse response, String userName, String password,
Integer state, String realName, String mobile, String email, Integer type, String card, String remark,
String roleIds) {
String logTitle ="";
JSONObject data = new JSONObject();
try {
} catch (Exception e) {
e.printStackTrace();
return ApiResultUtil.error();
}
return ApiResultUtil.success(null,logTitle,data);
}
5、jar 依赖
aspectjrt-1.9.6.jar
aspectjweaver-1.8.9.jar
spring-aspects-4.3.18.RELEASE.jar
6、工具类介绍
IpUtil 工具类
public class IpUtil {
public static String getIPAddress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-For:Squid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IP:apache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IP:weblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP:有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//X-Real-IP:nginx服务代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//还是不能获取到,最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
IPSeeker 工具类
用来读取QQwry.dat文件,以根据ip获得好友位置,网上有很多代码。
参考网站 :https://www.cnblogs.com/huiandong/articles/9223401.html