关于日志工具类
泛型日志工具类(LogUtil)
主要记录库表某条数据发生变化时,变化前后进行对比,进行打印
设计一个工具类,通过传入两个对象,获得属性值变化前后的值,同时以JSONArray的方式返回。
工具类代码
package com.fyhf.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author : qisw
* @desc : 存日志的辅助工具类 通过参入两个对象,能够以jsonarray的方式输出属性不同的值
* oldBean 表示修改之前的对象 newBean 表示修改之后的对象
* @date : 2019-11-21 17:41
*/
public class LogUtil<T> {
public JSONArray compareObject(Object oldBean, Object newBean) {
T pojo1 = (T) oldBean;
T pojo2 = (T) newBean;
JSONArray array = new JSONArray();
try {
Class clazz = pojo1.getClass();
Field[] oldFields = pojo1.getClass().getDeclaredFields();
Field[] newFields = pojo2.getClass().getDeclaredFields();
for (Field oldFileld: oldFields){
oldFileld.setAccessible(true);//设置属性可读
String old_name = oldFileld.getName();//获取属性名称
if(StringUtils.equalsIgnoreCase("id",old_name)){ //忽略id的比较
continue;
}
for(Field newFileld: newFields){
newFileld.setAccessible(true);
String new_name = newFileld.getName();//获取属性名称
if(StringUtils.equals(old_name,new_name)){
Object o1 = oldFileld.get(pojo1);//当前对象对应的属性值
Object o2 = newFileld.get(pojo2);//上一个对应的属性值
if (o1 == null || o2 == null) {
if(o1 == null && o2 == null){
continue;
}
JSONObject job = new JSONObject();
JSONObject job1 = new JSONObject();
job.put("before",o1);
job.put("after",o2);
job1.put(new_name,job);
array.add(job1);
continue;
}
//两个对象的属性值不一样 表示这个字段被修改过
if(!o1.toString().equals(o2.toString())){
JSONObject job = new JSONObject();
JSONObject job1 = new JSONObject();
job.put("before",o1);
job.put("after",o2);
job1.put(new_name,job);
array.add(job1);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
实体类代码
package com.example.demo;
/**
* @author : qisw
* @desc :
* @date : 2019-11-16 17:45
*/
public class Host {
private String ip;
private int port;
private String name;
private String cTime;
public String getcTime() {
return cTime;
}
public void setcTime(String cTime) {
this.cTime = cTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Host(String ip, int port, String name, String cTime) {
this.ip = ip;
this.port = port;
this.name = name;
this.cTime = cTime;
}
}
测试类代码
@Test
public void testLogUtil(){
Host host1 = new Host("135",8080,"host1","2018-03-01");
Host host2 = new Host("136",8081,"host2","2018-05-01");
LogUtil<Host> logUtil = new LogUtil<>();
JSONArray array = logUtil.compareObject(host1, host2);
System.out.println(array);
}