学习记录接口调用的日志注解
若依框架的日志注解
1.先创建日志注解(若依的日志是异步执行的)
InsertLog这个类里面写的是定义注解的参数
import java.lang.annotation.*;
/**
* 对外接口管理日志注解
* 此注解可以用在controller
*
* @author hanoch
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD }) //作用在参数和方法上
@Retention(RetentionPolicy.RUNTIME) //运行时注解
@Documented //表明这个注解应该被 javadoc工具记录
public @interface InsertLog {
public String description() default "";
//这个是要把这个日志想放到那个模块的controller上
public String modulesName() default "";
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
}
InsertLogAspect 切点类,这个是核心代码,写注解的日志在运行时,抛出异常时怎么处理,参数的拼接可以自定义模块
package com.tecsun.common.log.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.tecsun.common.core.constant.ServiceNameConstants;
import com.tecsun.common.core.domain.interfaces.ExterNalInterfaceLog;
import com.tecsun.common.core.utils.ServletUtils;
import com.tecsun.common.core.utils.StringUtils;
import com.tecsun.common.core.utils.ip.IpUtils;
import com.tecsun.common.log.annotation.InsertLog;
import com.tecsun.common.log.enums.BusinessStatus;
import com.tecsun.common.log.service.AsyncLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* Title: CardCenterLogAspect
* @date 2023年5月08日
* @version V1.0
* Description: 切点类
*/
@Aspect
@Component
public class InsertLogAspect
{
private static final Logger logger = LoggerFactory.getLogger(InsertLogAspect.class);
@Autowired
private AsyncLogService asyncLogService;
// 配置织入点
@Pointcut("@annotation(com.tecsun.common.log.annotation.InsertLog)")
public void logPoint()
{
}
// // 配置织入点
// @Pointcut("@annotation(com.tecsun.common.log.annotation.CardCenterLog)")
// public void controllerAspect()
// {
// }
/**
* @Description 前置通知 用于拦截Controller层记录用户的操作
* @date 2018年9月3日 10:38
*/
// @Before("controllerAspect()")
// public void doBefore(JoinPoint joinPoint){
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// HttpSession session = request.getSession();
// //读取session中的用户
// User user = (User) session.getAttribute("user");
//
// String ip = IpUtils.getIpAddr(request);
//
// try {
// //*========控制台输出=========*//
// System.out.println("==============前置通知开始==============");
// System.out.println("请求方法" (joinPoint.getTarget().getClass().getName() "." joinPoint.getSignature().getName()));
// System.out.println("方法描述:" getControllerMethodDescription(joinPoint));
// System.out.println("请求人:" user.getUsername());
// System.out.println("请求ip:" ip);
//
// //*========数据库日志=========*//
// Action action = new Action();
// action.setActionDes(getControllerMethodDescription(joinPoint));
// action.setActionType("0");
// action.setActionIp(ip);
// action.setUserId(user.getId());
// action.setActionTime(new Date());
// //保存数据库
// actionService.add(action);
//
// }catch (Exception e){
// //记录本地异常日志
// logger.error("==前置通知异常==");
// logger.error("异常信息:{}",e.getMessage());
// }
// }
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPoint()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPoint()", 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
{
// 获得注解
InsertLog controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// *========数据库日志=========*//
//注解存放的日志只适合放在接口管理的接口信息页面的表
ExterNalInterfaceLog log = new ExterNalInterfaceLog();
// 处理接口的参数
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
log.setUrl(className "." methodName "()");
// 设置请求方式
log.setInterfaceType(ServletUtils.getRequest().getMethod());
// 获取请求地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
log.setRequestAddress(ip);
if(jsonResult != null){
//出参返回
String jsonOut = JSON.toJSONString(jsonResult);
// JSONObject jsonOutObject = JSONObject.parseObject(jsonOut);
// 获取 响应状态码 设置请求状态
// if (jsonOutObject.containsKey(Result.CODE_TAG) && StringUtils.isNotBlank(jsonOutObject.getString(Result.CODE_TAG))) {
// log.setRequestTypeCode(jsonOutObject.getString(Result.CODE_TAG));
// }
// 设置 请求报文
log.setOutParams(jsonOut);
}
if (e != null)
{
log.setStatus(BusinessStatus.FAIL.ordinal());
log.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
getControllerMethodDescription(joinPoint, controllerLog, log);
String logJsonStr = JSON.toJSONString(log);
asyncLogService.saveCardCenterLog(logJsonStr);
}
catch (Exception exp)
{
// 记录本地异常日志
logger.error("==前置通知异常==");
logger.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param exterNalInterfaceLog 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, InsertLog log, ExterNalInterfaceLog exterNalInterfaceLog) throws Exception
{
// 是否需要保存request,参数和值
if (log.isSaveRequestData())
{
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, exterNalInterfaceLog,log.modulesName());
}
}
/**
* 获取请求的参数,放到log中
*
* @param exterNalInterfaceLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, ExterNalInterfaceLog exterNalInterfaceLog,String modulesName) throws Exception
{
String requestMethod = exterNalInterfaceLog.getInterfaceType();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))
{
//定制入参,根据modulesName拼接参数
//默认是卡中心接口模块的接口
//后面可以根据的模块去封装想要的参数
//后面自定义的参数可以放在if后面加条件
if (StringUtils.isBlank(modulesName) || modulesName.equals(ServiceNameConstants.CAR_SERVICE)){
argsArrayToString(joinPoint.getArgs(),exterNalInterfaceLog);
}
String param = JSON.toJSONString(exterNalInterfaceLog.getDataString());
exterNalInterfaceLog.setInParams(StringUtils.substring(param, 0, 2000));
}
}
/**
* 是否存在注解,如果存在就获取
*/
private InsertLog getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(InsertLog.class);
}
return null;
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray,ExterNalInterfaceLog exterNalInterfaceLog)
{
String params = "";
if (paramsArray != null && paramsArray.length > 0)
{
for (int i = 0; i < paramsArray.length; i )
{
if (!isFilterObject(paramsArray[i]))
{
try
{
BeanUtils.copyProperties(paramsArray[i], exterNalInterfaceLog);
Object jsonObj = JSON.toJSON(paramsArray[i]);
params = jsonObj.toString() " ";
getLogParams(exterNalInterfaceLog,params);
}
catch (Exception e)
{
}
}
}
}
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
|| o instanceof BindingResult;
}
/**
* 获取请求参数中的关键信息,并设置到Log对象中
* @param log 日志对象
* @param jsonObject 入参对象
*/
private void getLogParams(ExterNalInterfaceLog log, String jsonObject) {
try {
JSONObject jsonInObject = JSONObject.parseObject(jsonObject);
if (jsonInObject == null) {
throw new JSONException("JSON解析失败");
}
// 获取参数中的姓名 使用name
if (jsonInObject.containsKey("name") && StringUtils.isNotBlank(jsonInObject.getString("name"))) {
log.setName(jsonInObject.getString("name"));
}
// 获取参数中的姓名 使用 aac003
if (jsonInObject.containsKey("aac003") && StringUtils.isNotBlank(jsonInObject.getString("aac003"))) {
log.setName(jsonInObject.getString("aac003"));
}
// 获取入参中的身份证码 使用idNum
if (jsonInObject.containsKey("idNum") && StringUtils.isNotBlank(jsonInObject.getString("idNum"))) {
log.setIdNum(jsonInObject.getString("idNum"));
}
// 获取入参中的身份证码 使用aac002
if (jsonInObject.containsKey("aac002") && StringUtils.isNotBlank(jsonInObject.getString("aac002"))) {
log.setIdNum(jsonInObject.getString("aac002"));
}
// 获取入参中的身份证码 使用aac147
if (jsonInObject.containsKey("aac147") && StringUtils.isNotBlank(jsonInObject.getString("aac147"))) {
log.setIdNum(jsonInObject.getString("aac147"));
}
// 获取入参中的手机号码1
if (jsonInObject.containsKey("mobileNum") && StringUtils.isNotBlank(jsonInObject.getString("mobileNum"))) {
log.setPhone(jsonInObject.getString("mobileNum"));
}
// 获取入参中的手机号码2
if (jsonInObject.containsKey("mobile") && StringUtils.isNotBlank(jsonInObject.getString("mobile"))) {
log.setPhone(jsonInObject.getString("mobile"));
}
// 获取入参中的手机号码3
if (jsonInObject.containsKey("AAE005") && StringUtils.isNotBlank(jsonInObject.getString("AAE005"))) {
log.setPhone(jsonInObject.getString("AAE005"));
}
} catch (JSONException e) {
e.getMessage();
e.printStackTrace();
logger.info("JSON解析失败!");
}
}
}
AsyncLogService 远程调用插入数据库的方法(异步)
package com.tecsun.common.log.service;
import com.tecsun.system.api.RemoteInterfaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.tecsun.system.api.RemoteLogService;
import com.tecsun.system.api.domain.SysOperLog;
import javax.annotation.Resource;
/**
* 异步调用日志服务
*
* @author tecsun
*/
@Service
public class AsyncLogService
{
@Autowired
private RemoteLogService remoteLogService;
@Resource
RemoteInterfaceService remoteInterfaceService;
/**
* 保存系统日志记录
*/
@Async
public void saveSysLog(SysOperLog sysOperLog)
{
remoteLogService.saveLog(sysOperLog);
}
/**
* 对外接口保存系统日志记录
*/
@Async
public void saveCardCenterLog(String logJsonStr)
{
remoteInterfaceService.insertExternalInterfaceLog(logJsonStr);
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgbcafj
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01