操作日志工具类 Diff

概述

业务上经常会需要记录某些数据的操作明细, 出现事故可以追查到是谁于什么时间修改或删除了数据, 这就需要这些字段逐个进行 diff 记录, 下面是一个工具类

Diff 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.abc.utils;

import lombok.Data;

/**
* @author Catch
* @since 2021/3/4 11:45
*/
@Data
public class Diff {

private String template = "[%s]: %s -> %s\n";
private StringBuilder content = new StringBuilder();


public static Diff builder() {
return new Diff();
}

public String build() {
return this.getContent().toString();
}

public Diff diffField(String fieldName, String before, String after) {
// 处理 before 或 after 可能为 null 的情况, 并去除空格
before = (before == null || "null".equals(before)) ? "" : before.trim();
after = (after == null || "null".equals(after)) ? "" : after.trim();

if (before.equals(after)) {
return this;
}
this.getContent().append(String.format(template, fieldName, before, after));
return this;
}

}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.abc.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Test;

/**
* @author Catch
* @since 2021/3/4 12:12
*/
public class DiffTest {

@Test
public void testDiff() {
User before = new User(1L, "李明", 1, 19, "");
User after = new User(1L, "李华", null, 20, "工程师");

String operations = Diff.builder()
.diffField("姓名", before.getName(), after.getName())
.diffField("性别", formatGender(before.getGender()), formatGender(after.getGender()))
.diffField("年龄", String.valueOf(before.getAge()), String.valueOf(after.getAge()))
.diffField("职位", before.getPosition(), after.getPosition())
.build();

System.out.println(operations);
}

public String formatGender(Integer gender) {
if (gender == null) {
return null;
}
return gender == 1 ? "男" : "女";
}

@Data
@AllArgsConstructor
public static class User {

private Long id;
private String name;
private Integer gender;
private Integer age;
private String position;

}

}