一、背景:
後臺系統配置越來越多的出現需要進行日誌記錄的功能,且當前已有日誌記錄不可複用,需要統一日誌記錄格式,提高日誌記錄開發效率。
二、預期效果展示:
新建動作:
修改動作:
刪除動作:
三、資料儲存:
注:可以選擇其他儲存方式,這裡只簡單舉個例子
`biz_id` bigint(20) NOT NULL DEFAULT 0 COMMENT '業務id',
`biz_type` tinyint(4) NOT NULL DEFAULT 0 COMMENT '業務型別',
`operator_id` varchar(128) NOT NULL DEFAULT '' COMMENT '操作人',
`operate_content` text COMMENT '操作內容',
`change_before` text COMMENT '修改前',
`change_after` text COMMENT '修改後',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間'
四、原理簡述:
日誌構建關注兩個物件,一個是修改前,修改後:
修改前:null + 修改後:X = 新建
修改前:Y + 修改後:X = 更新
修改前:Y + 修改後:null = 刪除
修改內容判斷依據傳入的兩個物件,對兩個物件的每個屬性進行逐一對比,如果發生變化則是需要進行日誌記錄欄位;關注的屬性使用註解進行標註。
五、具體實現:
註解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface LogField {
String name() default "";
String valueFun() default "";
boolean spliceValue() default true;
}
name: name值表示該欄位如果被修改,應在日誌中記錄的欄位名;預設取欄位名
valueFun: 表示獲取改變欄位內容的獲取方法;預設取欄位值,若valueFun方法不存在,則取預設值
spliceValue: 日誌是否需要拼接變更內容,預設拼接
註解處理:
@Service
@Slf4j
public class OperateLogService {
@Resource
private CommonOperateLogService commonOperateLogService;
enum ActionEnum{
ADD("新建"),
UPDATE("修改"),
DELETE("刪除");
ActionEnum(String desc) {
this.desc = desc;
}
public String desc;
}
private int insertLog(CommonOperatorLog commonOperatorLog){
String result = commonOperateLogService.insertLog(JSON.toJSONString(commonOperatorLog));
Response response = JSON.parseObject(result, Response.class);
return Objects.isNull(response) || ApiResponse.Status.fail.equals(response.getStatus()) ? 0 : (int) response.getContent();
}
public PageOutput<CommonOperatorLog> queryList(Long bizId, Integer bizType, Integer pageNum, Integer pageSize){
String result = commonOperateLogService.queryLog(bizId, bizType, pageNum, pageSize);
PageOutput pageOutput = JSON.parseObject(result, new TypeReference<PageOutput<CommonOperatorLog>>() {});
return pageOutput;
}
public <T> void saveLog(String operatorId,Long bizId, Integer bizType, T target, T original){
if(StringUtils.isBlank(operatorId) || (Objects.isNull(target) && Objects.isNull(original))){
throw new IllegalArgumentException();
}
if(Objects.nonNull(target) && Objects.nonNull(original) && !target.getClass().isAssignableFrom(original.getClass())){
throw new IllegalArgumentException();
}
ActionEnum action = getAction(target, original);
List<Triple<String, String, LogField>> changeInfos = getChangeInfoList(target, original);
List<String> changeInfoList = new ArrayList<>();
if(CollectionUtils.isEmpty(changeInfos) && !ActionEnum.UPDATE.equals(action)){
changeInfoList.add(0, action.desc);
}else if (CollectionUtils.isEmpty(changeInfos)){
return;
}else {
changeInfoList = changeInfos.stream().map(i -> i.getRight().spliceValue() ?
action.desc + StringUtils.joinWith("為:", i.getLeft(), i.getMiddle()) :
action.desc + StringUtils.join("了", i.getLeft()))
.collect(Collectors.toList());
}
String operateContext = StringUtils.join(changeInfoList, "\n");
operateContext = operateContext.replaceAll("\"","")
.replaceAll("\\[","").replaceAll("\\]","");
CommonOperatorLog operatorLog = new CommonOperatorLog();
operatorLog.setBizId(bizId);
operatorLog.setBizType(bizType);
operatorLog.setOperateContent(operateContext);
operatorLog.setOperatorId(operatorId);
operatorLog.setChangeBefore(JSON.toJSONString(original));
operatorLog.setChangeAfter(JSON.toJSONString(target));
this.insertLog(operatorLog);
}
private ActionEnum getAction(Object target, Object original){
ActionEnum action = ActionEnum.ADD;
if(Objects.nonNull(target) && Objects.nonNull(original)){
action = ActionEnum.UPDATE;
}else if(Objects.nonNull(target)){
action = ActionEnum.ADD;
}else if (Objects.nonNull(original)){
action = ActionEnum.DELETE;
}
return action;
}
private<T> List<Triple<String, String, LogField>> getChangeInfoList(T target, T original){
if(Objects.isNull(target) || Objects.isNull(original)){
return new ArrayList<>();
}
List<Pair<Field, Object>> targetFields = allFields(target);
List<Pair<Field, Object>> originalFields = allFields(original);
if(targetFields.size() != originalFields.size()){
//理論上不可能執行到這
throw new IllegalArgumentException();
}
List<Triple<String, String, LogField>> result = new ArrayList<>();
for (int i = 0; i < targetFields.size(); i++) {
Pair<Field, Object> targetField = targetFields.get(i);
Pair<Field, Object> originalField = originalFields.get(i);
ReflectionUtils.makeAccessible(targetField.getKey());
ReflectionUtils.makeAccessible(originalField.getKey());
Object targetValue = ReflectionUtils.getField(targetField.getKey(), targetField.getValue());
Object originalValue = ReflectionUtils.getField(originalField.getKey(), originalField.getValue());
if(targetValue != originalValue && (Objects.isNull(targetValue) ||
(!targetValue.equals(originalValue) &&
compareTo(Pair.of(targetField.getKey(), targetValue), Pair.of(originalField.getKey(), originalValue)) &&
!JSON.toJSONString(targetValue).equals(JSON.toJSONString(originalValue))))){
result.add(Triple.of(getFieldName(targetField.getKey()), getFieldValue(targetField.getKey(), targetField.getValue()), targetField.getKey().getAnnotation(LogField.class)));
}
}
return result;
}
private boolean compareTo(Pair<Field, Object> targetField, Pair<Field, Object> originalField){
Field field = targetField.getKey();
Object targetValue = targetField.getValue();
Object originalValue = originalField.getValue();
boolean canCompare = Arrays.stream(field.getType().getInterfaces()).anyMatch(i -> Comparable.class.getName().equals(i.getName()));
if(canCompare && Objects.nonNull(targetValue) && Objects.nonNull(originalValue)){
Method compareTo = ReflectionUtils.findMethod(field.getType(), "compareTo", field.getType());
if(Objects.isNull(compareTo)){
return true;
}
Object compared = ReflectionUtils.invokeMethod(compareTo, targetValue, originalValue);
return (int)compared != 0 ;
}
return true;
}
private <T> List<Pair<Field, Object>> allFields(T obj){
List<Triple<Field, Object, Boolean>> targetField = findField(obj);
List<Triple<Field, Object, Boolean>> allField = Lists.newArrayList(targetField);
List<Triple<Field, Object, Boolean>> needRemove = new ArrayList<>();
for (int i = 0; i < allField.size(); i++) {
Triple<Field, Object, Boolean> fieldObjectDes = allField.get(i);
if(!fieldObjectDes.getRight()){
ReflectionUtils.makeAccessible(fieldObjectDes.getLeft());
Object fieldV = ReflectionUtils.getField(fieldObjectDes.getLeft(), fieldObjectDes.getMiddle());
List<Triple<Field, Object, Boolean>> fieldList = findField(fieldV);
if(CollectionUtils.isNotEmpty(fieldList)){
allField.addAll(fieldList);
needRemove.add(fieldObjectDes);
}
}
}
if(CollectionUtils.isNotEmpty(needRemove)){
allField.removeAll(needRemove);
}
return allField.stream().map(i->Pair.of(i.getLeft(), i.getMiddle())).collect(Collectors.toList());
}
private <T> List<Triple<Field, Object, Boolean>> findField(T obj){
Class<?> objClass = obj.getClass();
Field[] declaredFields = objClass.getDeclaredFields();
List<Field> allFields = Lists.newArrayList(declaredFields);
if(Objects.nonNull(objClass.getSuperclass())){
Field[] superClassFields = objClass.getSuperclass().getDeclaredFields();
allFields.addAll(Arrays.asList(superClassFields));
}
List<Triple<Field, Object, Boolean>> result = new ArrayList<>();
for (Field declaredField : allFields) {
LogField annotation = declaredField.getAnnotation(LogField.class);
if(Objects.nonNull(annotation)){
result.add(Triple.of(declaredField, obj, declaredField.getType().getPackage().getName().startsWith("java")));
}
}
return result;
}
private String getFieldName(Field field){
LogField annotation = field.getAnnotation(LogField.class);
String name = annotation.name();
if(StringUtils.isBlank(name)){
name = field.getName();
}
return name;
}
private <T> String getFieldValue(Field field, T targetObj){
LogField annotation = field.getAnnotation(LogField.class);
if(!annotation.spliceValue()){
return "";
}
String valueFun = annotation.valueFun();
if(StringUtils.isBlank(valueFun)){
Object fieldValue = ReflectionUtils.getField(field, targetObj);
return getStrValue(fieldValue);
}else {
Method valueMethod = ReflectionUtils.findMethod(targetObj.getClass(), valueFun);
if(Objects.isNull(valueMethod)){
Object fieldValue = ReflectionUtils.getField(field, targetObj);
return getStrValue(fieldValue);
}else {
ReflectionUtils.makeAccessible(valueMethod);
Object invokeMethodRes = ReflectionUtils.invokeMethod(valueMethod, targetObj);
return getStrValue(invokeMethodRes);
}
}
}
private String getStrValue(Object fieldValue){
List<String> emptyStr = ImmutableList.of("\"\"", "{}","[]");
String value = Objects.isNull(fieldValue) ? "無" : JSON.toJSONString(fieldValue);
return emptyStr.contains(value) ? "無" : value;
}
}
六、使用示例:
1、使用的日誌記錄物件(這個物件只為日誌服務)
public class SubsidyRateLog {
@LogField(name = "補貼率名稱")
private String name;
@LogField(name = "適用城市", valueFun = "getCityNames")
private List<Integer> cityIds;
private List<String> cityNames;
}
name是直接展示欄位,所以修改值即name本身的值;cityIds 是我們關心比較欄位,當它值不一樣時進行 欄位value 值獲取,這個值是展示在前端的,所以可以根據需要進行格式定義,預設是將取到的值進行toJSON;當前例子中獲取的是getCityNames方法返回的值;
2、無專用日誌物件(大多數時候我們有自己的實體物件,但不包含具體日誌描述欄位),需要進行繼承
public class SubsidyRate {
@LogField(name = "補貼率名稱")
private String name;
@LogField(name = "適用城市", valueFun = "getCityNames")
private List<Integer> cityIds;
}
@Data
public class SubsidyRateLog extends SubsidyRate{
private List<String> cityNames;
}
此方式適用於相容現有物件,而不去破壞現有物件的完整性
3、物件包含子物件(比較複雜的大物件,如Task中的券資訊)
public class SubsidyRateLog {
@LogField(name = "補貼率名稱")
private String name;
@LogField
private Address address;
}
public class Address {
@LogField(name = "省份")
private String province;
@LogField(name = "城市")
private String city;
}
此情況下會將所有資訊平鋪,如果 Address 中 沒有_LogField_ 註解,那麼會直接使用將獲取address值,如果存在註解,那麼將忽略address本身,只關注註解欄位。
作者:京東零售 祁偉
來源:京東雲開發者社群 轉載請註明來源