实现日志记录

比较两个json串,即实体修改前后的差异性记录。调用方法直接使用
campareJsonObject(String oldJsonStr, String newJsonStr1)

​
package com.hq.base.hqscm.log.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class CampareJson {
	
	private static String replaceFirst(String ret, String strToReplace, String replaceWithThis) {
		return ret.replaceFirst(strToReplace, replaceWithThis);
	}

	
	public static String replaceLast(String text, String strToReplace, String replaceWithThis) {
		return text.replaceFirst("(?s)" + strToReplace + "(?!.*?" + strToReplace + ")", replaceWithThis);
	}

	public String campareJsonObject(String oldJsonStr, String newJsonStr1) {
		StringBuffer sb = new StringBuffer();
		oldJsonStr = StringEscapeUtils.unescapeJava(oldJsonStr);
		oldJsonStr = StringEscapeUtils.unescapeJava(oldJsonStr);
		JSON oldJson = JSON.parseObject(oldJsonStr);
		JSON newJson = JSON.parseObject(newJsonStr1);
		Map<String, Object> oldMap = new LinkedHashMap<>();
		Map<String, Object> newMap = new LinkedHashMap<>();
		convertJsonToMap(oldJson, "", oldMap);
		convertJsonToMap(newJson, "", newMap);
		Map<String, Object> differenceMap = campareMap(oldMap, newMap, 1);
		Iterator<Map.Entry<String, Object>> iterator = differenceMap.entrySet().iterator();
		while (iterator.hasNext()) {
			LinkedList list = new LinkedList();
			Map.Entry<String, Object> entry = iterator.next();
			Object value = entry.getValue();
			if (value instanceof Map) {
				Map<String, Object> map = (Map) value;
				for (Object value2 : map.values()) {
					list.add(value2.toString());
				}
			}
			String message = null;
			try {
				message = ConfigInfo.getValue(entry.getKey());
			} catch (Exception e) {
				log.error("读取配置异常,{}", e);
			}

			Object o = list.removeLast();
			Object o1 = list.removeLast();
			try {
				if (entry.getKey().contains(".id")) {
					continue;
				}
				try {
					String ignore = ConfigInfo.getValue("ignore." + entry.getKey());
					if (StringUtils.isNotEmpty(ignore) && ignore.equals(ignore)) {
						continue;
					}
				}catch (Exception e){

				}

				if (ObjectUtil.isNotEmpty(o)) {
					if (StringUtils.isNotEmpty(o.toString())) {
						o = seto1(o, entry);
					}
				}

				if (ObjectUtil.isNotEmpty(o1)) {
					if (StringUtils.isNotEmpty(o1.toString())) {
						o1 = seto1(o1, entry);
					}
				}
				if((o != null && StringUtils.isEmpty(o.toString()) && (o1 != null && StringUtils.isEmpty(o1.toString())))){
					continue;
				}
				if (o != null && StringUtils.isEmpty(o.toString())) {
					o = "空";
				}
				if (o1 != null && StringUtils.isEmpty(o1.toString())) {
					o1 = "空";
				}
			} catch (Exception e) {

			}

			if (message == null) {
				sb.append("【" + entry.getKey() + "】:" + "由: 【" + o + "】" + " 修改为" + "【" + o1 + "】").append("rn");
			} else {
				sb.append("【" + message + "】:" + "由: 【" + o + "】" + " 修改为" + "【" + o1 + "】").append("rn");
			}
		}
		return sb.toString();
	}

	public String timestampToDate(long time) throws ParseException {
		String dateTime;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		long timeLong = Long.valueOf(time);
		dateTime = simpleDateFormat.format(new Date(timeLong));
		return dateTime;
	}


	private Object seto1(Object o1, Map.Entry<String, Object> entry) {

		if (entry.getKey().equals("orderGoodsVo.[1].expectDate") || entry.getKey().equals("orderGoodsVo.[0].expectDate")) {
			try {
				o1 = timestampToDate(Long.valueOf(o1.toString()));
			} catch (Exception e) {
				o1 = o1.toString();
				log.error("处理日志异常,{}", e);
			}
		}
		String message = ConfigInfo.getValue(entry.getKey() + o1.toString());
		if (StringUtils.isNotEmpty(message)) {
			return message;
		}
		return o1;
	}


	private void convertJsonToMap(Object json, String root, Map<String, Object> resultMap) {
		if (json instanceof JSONObject) {
			JSONObject jsonObject = ((JSONObject) json);
			Iterator iterator = jsonObject.keySet().iterator();
			while (iterator.hasNext()) {
				Object key = iterator.next();
				Object value = jsonObject.get(key);
				String newRoot = "".equals(root) ? key + "" : root + "." + key;
				if (value instanceof JSONObject || value instanceof JSONArray) {
					convertJsonToMap(value, newRoot, resultMap);
				} else {
					resultMap.put(newRoot, value);
				}
			}
		} else if (json instanceof JSONArray) {
			JSONArray jsonArray = (JSONArray) json;
			for (int i = 0; i < jsonArray.size(); i++) {
				Object vaule = jsonArray.get(i);
				String newRoot = "".equals(root) ? "[" + i + "]" : root + ".[" + i + "]";
				if (vaule instanceof JSONObject || vaule instanceof JSONArray) {
					convertJsonToMap(vaule, newRoot, resultMap);
				} else {
					resultMap.put(newRoot, vaule);
				}
			}
		}
	}

	private Map<String, Object> campareMap(Map<String, Object> oldMap, Map<String, Object> newMap, Integer status) {
		campareNewToOld(oldMap, newMap, status);
		campareOldToNew(oldMap);
		return oldMap;
	}

	private void campareOldToNew(Map<String, Object> oldMap) {
		for (Iterator<Map.Entry<String, Object>> it = oldMap.entrySet().iterator(); it.hasNext(); ) {
			Map.Entry<String, Object> item = it.next();
			String key = item.getKey();
			Object value = item.getValue();
			int lastIndex = key.lastIndexOf(".");
			if (!(value instanceof Map)) {
				Map<String, Object> differenceMap = new HashMap<>();
				differenceMap.put("oldValue", value);
				differenceMap.put("newValue", "");
				oldMap.put(key, differenceMap);
			}
		}
	}

	private void campareNewToOld(Map<String, Object> oldMap, Map<String, Object> newMap, Integer status) {
		if (status.equals(1)) {
			Iterator<String> iterator = oldMap.keySet().iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				if (!newMap.containsKey(key)) {
					iterator.remove();
				}
			}
		}

		for (Iterator<Map.Entry<String, Object>> it = newMap.entrySet().iterator(); it.hasNext(); ) {
			Map.Entry<String, Object> item = it.next();
			String key = item.getKey();
			Object newValue = item.getValue();
			Map<String, Object> differenceMap = new HashMap<>();
			int lastIndex = key.lastIndexOf(".");
			String lastPath = key.substring(lastIndex + 1).toLowerCase();
			if (oldMap.containsKey(key)) {
				Object oldValue = oldMap.get(key);
				if (newValue.equals(oldValue)) {
					oldMap.remove(key);
					continue;
				} else {
					differenceMap.put("oldValue", oldValue);
					differenceMap.put("newValue", newValue);
					oldMap.put(key, differenceMap);
				}
			} else {
				differenceMap.put("oldValue", "");
				differenceMap.put("newValue", newValue);
				oldMap.put(key, differenceMap);
			}
		}
	}
}

​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring AOP是一个强大的框架,可以帮助我们实现各种切面,其中包括日志记录。下面是实现日志记录的步骤: 1. 添加Spring AOP依赖 在Maven或Gradle中添加Spring AOP依赖。 2. 创建日志切面 创建一个用于记录日志的切面。这个切面可以拦截所有需要记录日志的方法。在这个切面中,我们需要使用@Aspect注解来声明这是一个切面,并使用@Pointcut注解来定义哪些方法需要被拦截。 ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void serviceMethods() {} @Around("serviceMethods()") public Object logServiceMethods(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法名,参数列表等信息 String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); // 记录日志 System.out.println("Method " + methodName + " is called with args " + Arrays.toString(args)); // 执行方法 Object result = joinPoint.proceed(); // 记录返回值 System.out.println("Method " + methodName + " returns " + result); return result; } } ``` 在上面的代码中,我们使用了@Around注解来定义一个环绕通知,它会在拦截的方法执行前后执行。在方法执行前,我们记录了该方法的名称和参数列表,然后在方法执行后记录了该方法的返回值。 3. 配置AOP 在Spring的配置文件中配置AOP。首先,我们需要启用AOP: ```xml <aop:aspectj-autoproxy/> ``` 然后,我们需要将创建的日志切面添加到AOP中: ```xml <bean id="loggingAspect" class="com.example.demo.aspect.LoggingAspect"/> <aop:config> <aop:aspect ref="loggingAspect"> <aop:pointcut id="serviceMethods" expression="execution(* com.example.demo.service.*.*(..))"/> <aop:around method="logServiceMethods" pointcut-ref="serviceMethods"/> </aop:aspect> </aop:config> ``` 在上面的代码中,我们将创建的日志切面声明为一个bean,并将其添加到AOP中。我们还定义了一个切入点,并将其与日志切面的方法进行关联。 4. 测试 现在,我们可以测试我们的日志记录功能了。在我们的业务逻辑中,所有匹配切入点的方法都会被拦截,并记录它们的输入和输出。我们可以在控制台中看到这些日志信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程治铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值