首页 > 其他分享 >日志AOP

日志AOP

时间:2023-05-06 15:25:45浏览次数:27  
标签:String ip request lubansoft AOP import 日志 com

@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented
public @interface OperLog {
String operModul() default ""; // 操作模块
OperLogTypeEnum operType(); // 操作类型
String operDesc() default ""; // 操作说明
}


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;
}
}

标签:String,ip,request,lubansoft,AOP,import,日志,com
From: https://www.cnblogs.com/Acaak/p/17377432.html

相关文章

  • 自动化框架——日志模块
    日志模块的使用(python的logging模块)一:简单使用   学习原因:学习logging模块是为了更直观的调试代码,虽然有prin语句可以调试,但是在批量执行自动化用例时需要logging模块来调试。如何简单使用:导入日志模块设置basicConfig就行,设置日志级别,日志格式,日志写入模式,日志文件名就可......
  • SLS日志查询遇到的一些问题
    SLS日志查询遇到的一些问题根据执行时间查询结果不准确的问题原因:索引类型造成的;解决:进入索引设置,改为double即可;注意,只对更改后的日志生效,之前的旧日志不生效;一些常用查询语句查询执行时间大于5秒的*and__topic__:访问记录日志andoperation_hours>5查询平均执行时......
  • filebeat+kafka_logstash+es进行日志分析
    filebeat+kafka_logstash+es进行日志分析目录一.将安装包上传至目标服务器(即日志所在的服务器)二.解压安装三.配置filebeat1.配置采集日志到logstash,这种配置适用于日志量较小的场景,Filebeat--->logstash,logstash直接解析filebeat2.配置采集日志至kafka,file......
  • 统一controller的日志记录
    定义切面,然后匹配controller,around进行log打印@Slf4j@Component@AspectpublicclassControllerLogAspect{@Pointcut("execution(*delta.main.controller..*(..))")publicvoidrequestServer(){}@SneakyThrows@Around("requestServer(......
  • SpringBoot配置mongodb打印日志
    在application.yml添加配置:logging:level:org.springframework.data.mongodb.core.MongoTemplate:DEBUG如果使用的是application.properties,则是:logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG......
  • Spring17_基于XML的AOP开发10
    一、快速入门1. 导入AOP相关坐标2. 创建目标接口和目标类(内部有切点)3. 创建切面类(内部有增强方法)4. 将目标类和切面类的对象创建权交给spring5. 在applicationContext.xml中配置织入关系6. 测试代码代码实现:新建一个module:itheima_spring_aop1.......
  • Linux上定期清空持续输出的日志文件
    Linux定期清空持续输出的日志文件的方法(nohup)前言在nohup输出文件过程中,很容易出现输出日志文件过大的问题,网上的炫技大佬们太多了,让愚钝的阿瓜很难一下子捕捉到关键信息,虽然方法很简单,但阿瓜记性很差,难免以后不会手忙脚乱,故记录一下阿瓜找到的在不打断进程的条件下定期清空文件......
  • 日志查询常用命令
    tailtail-fa.log实时显示日志输出Ctrl+c退出tail-n10a.log显示日志倒数10行tail-n+10a.log显示第10行到最后行headcattac反向cata.log一次查看这个日志cat-na.log一次查看整个日志并且编上行号包括空白行cata.log|more显示满屏暂停,空格翻页,Ctrl+B返回......
  • Linux 日志 | 常用系统日志
    为了保证Linux系统正常运行,遇到问题时能及时解决,高效分析系统日志是非常必要的。Linux系统中的日志驱动进程通常为syslog,系统日志都可在syslog配置文件中配置。我们可以通过调用syslog的接口进行log,syslogd在取到log后进行处理,根据配置,将log保存到本地或发送到其......
  • GC日志分析之配置参数
    一、常用的GC参数我们从简单到复杂,一步一步来验证前面学习的知识,学会使用,加深巩固。启动示例程序如果是在IDEA、Eclipse等集成开发环境中,直接在文件中点击鼠标右键,选择“Run…”即可执行。如果使用JDK命令行,则可以使用javac工具来编译,使用java命令来执行(还记得吗?JDK......