Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Unified Operation Logging with Annotation-Driven Field Diff Detection in Java

This article presents a unified operation logging framework using Java annotations and reflection to automatically detect field changes between object states, generating structured audit logs for create, update, and delete actions with customizable field formatting and nested object support.

Background

Backend systems increasingly require operation logging, but existing logging implementations are not reusable. The goal is to unify log format and improve development efficiency.

Expected Effects

The solution produces structured logs for three action types:

Create : before=null, after=X

Update : before=Y, after=X

Delete : before=Y, after=null

Screenshots illustrate the log output for each action (images omitted).

Data Storage

A sample MySQL table stores logs:

`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 '创建时间'

Principle

The log builder compares two objects — before and after — field by field. Fields to be tracked are marked with a custom annotation. The comparison determines the action type and which fields changed.

Implementation

Annotation Definition

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface LogField {
    String name() default "";
    String valueFun() default "";
    boolean spliceValue() default true;
}

name : display name in log; defaults to field name.

valueFun : method to retrieve formatted value; defaults to field value.

spliceValue : whether to concatenate change description; default true.

Core Service: OperateLogService

The service uses reflection to traverse all fields (including superclass fields) of the before/after objects, filters fields annotated with @LogField, compares values, and builds log entries.

Action Detection

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;
}

Field Collection

allFields()

recursively collects fields from the object and its superclasses. findField() returns only fields annotated with @LogField, marking JDK built-in types (package starting with "java") as leaf nodes to stop recursion.

Value Comparison

For each paired field, the service:

Makes fields accessible via ReflectionUtils.

Retrieves values from both objects.

Checks inequality: reference difference, equals() mismatch, Comparable.compareTo() non-zero (if implemented), or JSON string difference.

If changed, records field name, formatted value, and annotation.

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;
}

Value Formatting

getFieldValue()

uses valueFun if provided and the method exists; otherwise returns JSON string of field value. Empty JSON ( "", {}, []) becomes "无".

Log Assembly

Changed fields are formatted as "Action fieldName为:newValue" (if spliceValue) or "Action了fieldName". Multiple changes joined by newline. Quotes and brackets stripped. Final log persisted via CommonOperateLogService.

Usage Examples

1. Dedicated Log Object

public class SubsidyRateLog {
    @LogField(name = "补贴率名称")
    private String name;
    @LogField(name = "适用城市", valueFun = "getCityNames")
    private List<Integer> cityIds;
    private List<String> cityNames;
}
name

logs its direct value. cityIds triggers comparison; when changed, getCityNames() provides display value.

2. Inheritance for Existing Entities

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;
}

Preserves original entity integrity while adding log-specific fields.

3. Nested Objects

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;
}

If nested object has @LogField fields, they are flattened into the log; otherwise the whole object value is used.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentReflectionLoggingAnnotationOperation LogAudit TrailField Comparison

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion