java獲取日誌記錄通用工具類
阿新 • • 發佈:2019-01-23
日誌註解類:
/** * 日誌註解類 * * @author: Rodge * @time: 2018年10月07日 下午11:29:10 * @version: V1.0.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface LogField { /** * 列名 */ public String name() default ""; /** * 實體屬性列名 */ public String entityName() default ""; }
日誌內容常量類:
package cn.com.javatest.constant; import java.util.HashMap; import java.util.Map; /** * 日誌內容常量類 * * @author: Rodge * @time: 2018年10月07日 下午11:30:43 * @version: V1.0.0 */ public final class LogConstant { /** * 測試日誌常量內容 * * @return */ public static Map<String, String> testConstant() { Map<String, String> map = new HashMap<>(); map.put("測試:0", "測試:正常"); map.put("測試:1", "測試:刪除"); map.put("測試:2", "測試:稽核"); return map; } }
日誌工具類:
package cn.com.javatest.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ReflectionUtils; import com.alibaba.fastjson.JSON; import cn.com.javatest.annotation.LogField; /** * 日誌操作工具類 * * @author: Rodge * @time: 2018年10月07日 下午11:31:24 * @version: V1.0.0 */ public final class LogUtils { /**日誌物件**/ private static final Logger LOGGER = LoggerFactory.getLogger(LogUtils.class); /**操作型別:add 新增**/ private static final String ADD_TYPE = "add"; /**操作型別:update 修改**/ private static final String UPDATE_TYPE = "update"; /** * 獲取新增操作的日誌內容 * * @param obj 頁面物件,必傳 * @param objMap 物件日誌常量內容,不必傳 * @return String 獲取操作後日志 */ public static String getAddLogs(Object obj, Map<String, String> objMap) { Map<String, String> dtoMap = getValues(obj, obj.getClass().getDeclaredFields(), ADD_TYPE); Map<String, String> childDtoMap = getChildValues(obj, obj.getClass().getDeclaredFields(), ADD_TYPE); if (!childDtoMap.isEmpty()) { dtoMap.putAll(childDtoMap); } StringBuilder after = new StringBuilder(); dtoMap.forEach((k, v) -> { after.append(k + v + ","); }); LOGGER.info("新增日誌內容:" + JSON.toJSONString(dtoMap)); String afterLog = after.toString(); if (StringUtils.isNotBlank(afterLog)) { return replaceLogs(afterLog.substring(0, afterLog.lastIndexOf(",")), objMap); } return null; } /** * 獲取修改操作的日誌內容 * * @param obj1 資料庫物件,必傳 * @param obj2 頁面物件,必傳 * @param objMap 物件日誌常量內容,不必傳 * @return map.get("before")獲取操作前日誌,map.get("after")獲取操作後日志 */ public static Map<String, String> getUpdateLogs(Object obj1, Object obj2, Map<String, String> objMap) { // 操作前 Map<String, String> entityMap = getValues(obj1, obj1.getClass().getDeclaredFields(), UPDATE_TYPE); Map<String, String> childEntityMap = getChildValues(obj1, obj1.getClass().getDeclaredFields(), UPDATE_TYPE); if (!childEntityMap.isEmpty()) { entityMap.putAll(childEntityMap); } LOGGER.info("對比前內容1:" + JSON.toJSONString(entityMap)); // 操作後 Map<String, String> dtoMap = getValues(obj2, obj2.getClass().getDeclaredFields(), UPDATE_TYPE); Map<String, String> childDtoMap = getChildValues(obj2, obj2.getClass().getDeclaredFields(), UPDATE_TYPE); if (!childDtoMap.isEmpty()) { dtoMap.putAll(childDtoMap); } LOGGER.info("對比前內容2:" + JSON.toJSONString(dtoMap)); StringBuilder before = new StringBuilder(); StringBuilder after = new StringBuilder(); entityMap.forEach((k, v) -> { if (dtoMap.containsKey(k) && !v.equals(dtoMap.get(k))) { before.append(k + v + ","); after.append(k + dtoMap.get(k) + ","); } }); LOGGER.info("對比後內容1:" + JSON.toJSONString(before)); LOGGER.info("對比後內容2:" + JSON.toJSONString(after)); String beforeLog = before.toString(); String afterLog = after.toString(); if (StringUtils.isNotBlank(beforeLog)) { Map<String, String> map = new HashMap<>(2); map.put("before", replaceLogs(beforeLog.substring(0, beforeLog.lastIndexOf(",")), objMap)); map.put("after", replaceLogs(afterLog.substring(0, afterLog.lastIndexOf(",")), objMap)); LOGGER.info("最終比對內容為:" + JSON.toJSONString(map)); return map; } return null; } /** * 日誌常量內容替換 * * @param logs 日誌內容 * @param objMap 日誌常量內容 * @return */ private static String replaceLogs(String logs, Map<String, String> objMap) { if (StringUtils.isNotBlank(logs) && objMap != null && !objMap.isEmpty()) { String[] contents = logs.split(","); for (int i = 0; i < contents.length; i++) { for (Map.Entry<String, String> entry : objMap.entrySet()) { if (entry.getKey().equals(contents[i])) { contents[i] = entry.getValue(); break; } } } return StringUtils.join(contents, ","); } return logs; } /** * 獲取物件註解內容、屬性值 * * @param t 實體物件 * @param fields 操作註解的物件 * @param operateType 操作型別:add 新增, update 修改 * @return */ private static Map<String, String> getValues(Object t, Field[] fields, String operateType) { Map<String, String> map = new LinkedHashMap<>(); for (Field field : fields) { LogField annotation = field.getAnnotation(LogField.class); if (annotation != null && StringUtils.isNotBlank(annotation.name())) { Class<?> type = field.getType(); String fieldName = field.getName(); String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method method = ReflectionUtils.findMethod(t.getClass(), methodName); if (method != null) { Object value = ReflectionUtils.invokeMethod(method, t); if (ADD_TYPE.equals(operateType)) { if (value != null && StringUtils.isNotBlank(value + "")) { map.put(annotation.name(), type == Date.class ? DateFormatUtils.format((Date)value, "yyyy-MM-dd HH:mm:ss") : String.valueOf(value)); } continue; } if (value == null || StringUtils.isBlank(value + "") || "null".equals(value)) { map.put(annotation.name(), "空"); } else { map.put(annotation.name(), type == Date.class ? DateFormatUtils.format((Date)value, "yyyy-MM-dd HH:mm:ss") : String.valueOf(value)); } } } } return map; } /** * 查詢實體類內的實體物件屬性,並處理之 * * @param fields 操作註解的物件 * @param operateType 操作型別:add 新增, update 修改 * @return */ private static Map<String, String> getChildValues(Object t, Field[] fields, String operateType) { Map<String, String> map = new LinkedHashMap<>(); for (Field field : fields) { LogField annotation = field.getAnnotation(LogField.class); if (annotation != null && StringUtils.isNotBlank(annotation.entityName())) { String fieldName = field.getName(); String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method method = ReflectionUtils.findMethod(t.getClass(), methodName); if (method != null) { Object value = ReflectionUtils.invokeMethod(method, t); if (value != null) { Map<String, String> mapChild = getValues(value, value.getClass().getDeclaredFields(), operateType); map.putAll(mapChild); } } } } return map; } }