Browse Source

2025-11-27

新增系统日志管理
master
fengyuan_yang 2 months ago
parent
commit
c1f69482fc
  1. 70
      src/main/java/com/gaotao/modules/sys/controller/SystemLogController.java
  2. 52
      src/main/java/com/gaotao/modules/sys/dao/SystemLogDao.java
  3. 34
      src/main/java/com/gaotao/modules/sys/service/SystemLogService.java
  4. 414
      src/main/java/com/gaotao/modules/sys/service/impl/SystemLogServiceImpl.java
  5. 183
      src/main/resources/mapper/sys/SystemLogDao.xml

70
src/main/java/com/gaotao/modules/sys/controller/SystemLogController.java

@ -0,0 +1,70 @@
package com.gaotao.modules.sys.controller;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.common.utils.R;
import com.gaotao.modules.sys.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 系统日志管理
*/
@RestController
@RequestMapping("/sys/systemLog")
public class SystemLogController {
@Autowired
private SystemLogService systemLogService;
/**
* 查询系统日志列表
*/
@PostMapping("/list")
public R list(@RequestBody Map<String, Object> params) {
PageUtils page = systemLogService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 查询系统日志参数详情
*/
@PostMapping("/getParams")
public R getParams(@RequestBody Map<String, Object> params) {
String site = (String) params.get("site");
String buNo = (String) params.get("buNo");
String requestId = (String) params.get("requestId");
Integer requestGroupId = params.get("requestGroupId") != null ?
Integer.parseInt(params.get("requestGroupId").toString()) : null;
return systemLogService.getParams(site, buNo, requestId, requestGroupId);
}
/**
* 批量删除系统日志
*/
@PostMapping("/delete")
public R delete(@RequestBody Map<String, Object> params) {
Object[] idsObj = (Object[]) params.get("ids");
Long[] ids = new Long[idsObj.length];
for (int i = 0; i < idsObj.length; i++) {
ids[i] = Long.parseLong(idsObj[i].toString());
}
return systemLogService.deleteBatch(ids);
}
/**
* 批量手动重试系统接口
*/
@PostMapping("/retryInterface")
public R retryInterface(@RequestBody Map<String, Object> params) {
@SuppressWarnings("unchecked")
java.util.List<Map<String, Object>> retryList = (java.util.List<Map<String, Object>>) params.get("retryList");
return systemLogService.batchRetryInterface(retryList);
}
}

52
src/main/java/com/gaotao/modules/sys/dao/SystemLogDao.java

@ -0,0 +1,52 @@
package com.gaotao.modules.sys.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gaotao.modules.sys.entity.ApiLogEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 系统日志DAO
*/
@Mapper
public interface SystemLogDao extends BaseMapper<ApiLogEntity> {
/**
* 查询系统日志列表
*/
List<Map<String, Object>> queryList(Map<String, Object> params);
/**
* 查询系统日志总数
*/
int queryTotal(Map<String, Object> params);
/**
* 批量删除
*/
int deleteBatch(@Param("ids") Long[] ids);
/**
* 根据sitebuNorequestIdrequestGroupId查询api_log记录
*/
Map<String, Object> getApiLog(@Param("site") String site,
@Param("buNo") String buNo,
@Param("requestId") String requestId,
@Param("requestGroupId") Integer requestGroupId);
/**
* 更新接口重试信息
*/
int updateRetryInfo(@Param("site") String site,
@Param("buNo") String buNo,
@Param("requestId") String requestId,
@Param("requestGroupId") Integer requestGroupId,
@Param("statusCode") String statusCode,
@Param("message") String message,
@Param("lastResponseData") String lastResponseData,
@Param("retryCount") Integer retryCount);
}

34
src/main/java/com/gaotao/modules/sys/service/SystemLogService.java

@ -0,0 +1,34 @@
package com.gaotao.modules.sys.service;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.common.utils.R;
import java.util.List;
import java.util.Map;
/**
* 系统日志Service
*/
public interface SystemLogService {
/**
* 查询系统日志列表
*/
PageUtils queryPage(Map<String, Object> params);
/**
* 查询系统日志参数详情
*/
R getParams(String site, String buNo, String requestId, Integer requestGroupId);
/**
* 批量删除系统日志
*/
R deleteBatch(Long[] ids);
/**
* 批量重试系统接口
*/
R batchRetryInterface(List<Map<String, Object>> retryList);
}

414
src/main/java/com/gaotao/modules/sys/service/impl/SystemLogServiceImpl.java

@ -0,0 +1,414 @@
package com.gaotao.modules.sys.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.common.utils.R;
import com.gaotao.modules.sys.dao.ApiInterfaceDao;
import com.gaotao.modules.sys.dao.ApiLogValuesDetailDao;
import com.gaotao.modules.sys.dao.ApiLogValuesHeadDao;
import com.gaotao.modules.sys.dao.SystemLogDao;
import com.gaotao.modules.sys.entity.ApiInterfaceEntity;
import com.gaotao.modules.sys.service.SystemLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import java.util.*;
/**
* 系统日志服务实现
*/
@Service("systemLogService")
public class SystemLogServiceImpl implements SystemLogService {
private static final Logger logger = LoggerFactory.getLogger(SystemLogServiceImpl.class);
@Autowired
private SystemLogDao systemLogDao;
@Autowired
private ApiLogValuesHeadDao apiLogValuesHeadDao;
@Autowired
private ApiLogValuesDetailDao apiLogValuesDetailDao;
@Autowired
private ApiInterfaceDao apiInterfaceDao;
@Autowired
private RestTemplate restTemplate;
@Override
public PageUtils queryPage(Map<String, Object> params) {
// 获取分页参数
int page = Integer.parseInt(params.getOrDefault("page", 1).toString());
int limit = Integer.parseInt(params.getOrDefault("limit", 10).toString());
// 计算offset
int offset = (page - 1) * limit;
params.put("offset", offset);
params.put("limit", limit);
// 查询列表
List<Map<String, Object>> list = systemLogDao.queryList(params);
// 查询总数
int total = systemLogDao.queryTotal(params);
// 构造分页结果
PageUtils pageUtil = new PageUtils(list, total, limit, page);
return pageUtil;
}
@Override
public R getParams(String site, String buNo, String requestId, Integer requestGroupId) {
try {
// 查询主表数据
Map<String, Object> head = apiLogValuesHeadDao.queryHead(site, buNo, requestId, requestGroupId);
// 查询明细数据
List<Map<String, Object>> detailList = apiLogValuesDetailDao.queryDetailList(site, buNo, requestId, requestGroupId);
// 构造返回的JSON结构
Map<String, Object> result = new LinkedHashMap<>();
// 处理主表数据将orderref1-20映射为"接口参数1"-"接口参数20"
if (head != null) {
for (int i = 1; i <= 20; i++) {
String key = "orderref" + i;
Object value = head.get(key);
if (value != null && !value.toString().trim().isEmpty()) {
result.put("接口参数" + i, value);
}
}
}
// 处理明细数据
if (detailList != null && !detailList.isEmpty()) {
List<Map<String, Object>> detailResultList = new ArrayList<>();
for (Map<String, Object> detail : detailList) {
Map<String, Object> detailResult = new LinkedHashMap<>();
for (int i = 1; i <= 20; i++) {
String key = "orderref" + i;
Object value = detail.get(key);
if (value != null && !value.toString().trim().isEmpty()) {
detailResult.put("接口参数" + i, value);
}
}
if (!detailResult.isEmpty()) {
detailResultList.add(detailResult);
}
}
if (!detailResultList.isEmpty()) {
result.put("DetailList", detailResultList);
}
}
return R.ok().put("params", result);
} catch (Exception e) {
logger.error("查询系统日志参数失败", e);
return R.error("查询系统日志参数失败: " + e.getMessage());
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public R deleteBatch(Long[] ids) {
try {
if (ids == null || ids.length == 0) {
return R.error("请选择要删除的记录");
}
int count = systemLogDao.deleteBatch(ids);
return R.ok().put("count", count);
} catch (Exception e) {
logger.error("批量删除系统日志失败", e);
return R.error("批量删除失败: " + e.getMessage());
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public R batchRetryInterface(List<Map<String, Object>> retryList) {
try {
if (retryList == null || retryList.isEmpty()) {
return R.error("请选择要重试的记录");
}
logger.info("批量手动重试系统接口开始,记录数: {}", retryList.size());
int successCount = 0;
int failureCount = 0;
int errorCount = 0;
List<Map<String, Object>> detailResults = new ArrayList<>();
// 遍历每个需要重试的记录
for (Map<String, Object> retryItem : retryList) {
String site = (String) retryItem.get("site");
String buNo = (String) retryItem.get("buNo");
String requestId = (String) retryItem.get("requestId");
Integer requestGroupId = retryItem.get("requestGroupId") != null ?
Integer.parseInt(retryItem.get("requestGroupId").toString()) : null;
String interfaceName = (String) retryItem.get("interfaceName");
Map<String, Object> detailResult = new LinkedHashMap<>();
detailResult.put("interfaceName", interfaceName);
detailResult.put("requestId", requestId);
try {
// 调用单个重试方法
R result = retrySingleInterface(site, buNo, requestId, requestGroupId);
if (result.get("code").equals(0)) {
@SuppressWarnings("unchecked")
Map<String, Object> retryResult = (Map<String, Object>) result.get("result");
String flag = (String) retryResult.get("flag");
if ("success".equalsIgnoreCase(flag)) {
successCount++;
detailResult.put("status", "success");
detailResult.put("u8CCode", retryResult.get("u8CCode"));
detailResult.put("message", "调用成功");
} else {
failureCount++;
detailResult.put("status", "failure");
detailResult.put("message", retryResult.get("errMsg"));
}
} else {
failureCount++;
detailResult.put("status", "failure");
detailResult.put("message", result.get("msg"));
}
} catch (Exception e) {
errorCount++;
detailResult.put("status", "error");
detailResult.put("message", "重试异常: " + e.getMessage());
logger.error("重试系统接口异常,requestId: {}", requestId, e);
}
detailResults.add(detailResult);
}
logger.info("批量手动重试完成,成功: {}, 失败: {}, 异常: {}", successCount, failureCount, errorCount);
// 返回批量结果
Map<String, Object> batchResult = new HashMap<>();
batchResult.put("successCount", successCount);
batchResult.put("failureCount", failureCount);
batchResult.put("errorCount", errorCount);
batchResult.put("totalCount", retryList.size());
batchResult.put("details", detailResults);
return R.ok().put("result", batchResult);
} catch (Exception e) {
logger.error("批量手动重试系统接口失败", e);
return R.error("批量手动重试失败: " + e.getMessage());
}
}
/**
* 重试单个接口
*/
private R retrySingleInterface(String site, String buNo, String requestId, Integer requestGroupId) {
try {
logger.info("手动重试系统接口开始,site: {}, buNo: {}, requestId: {}, requestGroupId: {}",
site, buNo, requestId, requestGroupId);
// 1. 查询api_log记录
Map<String, Object> apiLog = systemLogDao.getApiLog(site, buNo, requestId, requestGroupId);
if (apiLog == null) {
logger.error("未找到系统日志记录");
return R.error("未找到系统日志记录");
}
String interfaceName = (String) apiLog.get("interfaceName");
Integer retryCount = apiLog.get("retryCount") != null ? (Integer) apiLog.get("retryCount") : 0;
logger.info("查询到接口名称: {}, 当前重试次数: {}", interfaceName, retryCount);
// 2. 查询api_Interface获取接口IP和路径
ApiInterfaceEntity apiInterface = apiInterfaceDao.getByInterfaceName(site, buNo, interfaceName);
if (apiInterface == null) {
logger.error("未找到接口配置,interfaceName: {}", interfaceName);
return R.error("未找到接口配置: " + interfaceName);
}
String interfaceUrl = "http://" + apiInterface.getInterfaceIp() + apiInterface.getInterfaceValue();
logger.info("接口URL: {}", interfaceUrl);
// 3. 查询api_log_values_head主表数据
Map<String, Object> headData = apiLogValuesHeadDao.queryHead(site, buNo, requestId, requestGroupId);
// 4. 查询api_log_values_detail明细数据
List<Map<String, Object>> detailList = apiLogValuesDetailDao.queryDetailList(site, buNo, requestId, requestGroupId);
// 5. 构造JSON请求体
Map<String, Object> requestBody = new LinkedHashMap<>();
// 5.1 处理主表数据orderref1-20
if (headData != null) {
for (int i = 1; i <= 20; i++) {
String key = "orderref" + i;
Object value = headData.get(key);
if (value != null && !value.toString().trim().isEmpty()) {
// 根据字段位置映射到实际的字段名
String fieldName = getFieldName(i, true);
requestBody.put(fieldName, value);
}
}
}
// 5.2 处理明细数据
if (detailList != null && !detailList.isEmpty()) {
List<Map<String, Object>> detailResultList = new ArrayList<>();
for (Map<String, Object> detail : detailList) {
Map<String, Object> detailItem = new LinkedHashMap<>();
for (int i = 1; i <= 20; i++) {
String key = "orderref" + i;
Object value = detail.get(key);
if (value != null && !value.toString().trim().isEmpty()) {
// 根据字段位置映射到实际的字段名
String fieldName = getFieldName(i, false);
detailItem.put(fieldName, value);
}
}
if (!detailItem.isEmpty()) {
detailResultList.add(detailItem);
}
}
if (!detailResultList.isEmpty()) {
requestBody.put("DetailList", detailResultList);
}
}
logger.info("构造的请求体: {}", JSON.toJSONString(requestBody));
// 6. 调用外部接口
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestBody), headers);
String statusCode = "ERROR";
String message = "";
String lastResponseData = "";
try {
ResponseEntity<String> response = restTemplate.exchange(interfaceUrl, HttpMethod.POST, requestEntity, String.class);
lastResponseData = response.getBody();
logger.info("接口返回: {}", lastResponseData);
// 7. 解析返回结果
JSONObject responseJson = JSON.parseObject(lastResponseData);
String flag = responseJson.getString("Flag");
if ("success".equalsIgnoreCase(flag)) {
statusCode = "SUCCESS";
message = "接口调用成功";
String u8CCode = responseJson.getString("U8CCode");
if (u8CCode != null && !u8CCode.isEmpty()) {
message += ",U8单号: " + u8CCode;
}
} else {
statusCode = "FAILURE";
message = responseJson.getString("ErrMsg");
if (message == null || message.isEmpty()) {
message = "接口调用失败";
}
}
} catch (Exception e) {
statusCode = "ERROR";
message = "接口调用异常: " + e.getMessage();
lastResponseData = e.toString();
logger.error("调用外部接口异常", e);
}
// 8. 更新api_log记录
int updateCount = systemLogDao.updateRetryInfo(
site, buNo, requestId, requestGroupId,
statusCode, message, lastResponseData, retryCount + 1
);
logger.info("更新系统日志记录,更新条数: {}", updateCount);
// 9. 返回结果
Map<String, Object> result = new HashMap<>();
result.put("flag", "success".equalsIgnoreCase(statusCode) ? "success" : "failure");
result.put("u8CCode", "");
result.put("errMsg", message);
if (lastResponseData != null && !lastResponseData.isEmpty()) {
try {
JSONObject responseJson = JSON.parseObject(lastResponseData);
if (responseJson.containsKey("U8CCode")) {
result.put("u8CCode", responseJson.getString("U8CCode"));
}
} catch (Exception ignored) {
}
}
return R.ok().put("result", result);
} catch (Exception e) {
logger.error("手动重试系统接口失败", e);
return R.error("手动重试失败: " + e.getMessage());
}
}
/**
* 根据字段位置获取实际的字段名
* 这个映射关系需要根据实际接口文档来配置
*/
private String getFieldName(int position, boolean isHead) {
if (isHead) {
// 主表字段映射
switch (position) {
case 1: return "MESCCode";
case 2: return "KdType";
case 3: return "DDate";
case 4: return "CRdCode";
case 5: return "CMemo";
case 6: return "CWhCode";
case 7: return "CCusOAddress";
case 8: return "CDepCode";
default: return "orderref" + position;
}
} else {
// 明细表字段映射
switch (position) {
case 1: return "MESIrowNo";
case 2: return "OutCode";
case 3: return "OutIrowNo";
case 4: return "CInvCode";
case 5: return "IQuantity";
case 6: return "CBatch";
case 7: return "CbMemo";
case 8: return "CWhCode";
case 9: return "OutMocode";
case 10: return "OutIrowNo_zj";
case 11: return "NumberOfCases";
default: return "orderref" + position;
}
}
}
}

183
src/main/resources/mapper/sys/SystemLogDao.xml

@ -0,0 +1,183 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gaotao.modules.sys.dao.SystemLogDao">
<!-- 查询系统日志列表 -->
<select id="queryList" resultType="map">
SELECT
a.id,
a.site,
a.bu_no AS buNo,
a.request_id AS requestId,
a.interface_name AS interfaceName,
a.request_group_id AS requestGroupId,
a.re_document_no AS reDocumentNo,
a.re_document_type AS reDocumentType,
a.order_no AS orderNo,
a.seq_no AS seqNo,
a.status_code AS statusCode,
a.message,
a.source_system AS sourceSystem,
a.target_system AS targetSystem,
a.need_retry_flag AS needRetryFlag,
a.retry_count AS retryCount,
a.max_retry_count AS maxRetryCount,
a.retry_interval AS retryInterval,
a.next_retry_time AS nextRetryTime,
a.last_retry_time AS lastRetryTime,
a.warehouse_id AS warehouseId,
a.created_by AS createdBy,
a.created_date AS createdDate,
b.interface_type AS interfaceType
FROM api_log as a
left join api_Interface as b on a.interface_name = b.interface_name AND a.site = b.site and a.bu_no = b.bu_no
<where>
a.site in (select site from AccessSite where userID = #{userName})
and a.bu_no in (select bu_no from AccessBu where username = #{userName})
and type &lt;&gt; 'Interface'
<if test="interfaceName != null and interfaceName.trim() != ''">
AND a.interface_name LIKE '%' + #{interfaceName} + '%'
</if>
<if test="requestId != null and requestId.trim() != ''">
AND a.request_id = #{requestId}
</if>
<if test="reDocumentNo != null and reDocumentNo.trim() != ''">
AND a.re_document_no LIKE '%' + #{reDocumentNo} + '%'
</if>
<if test="reDocumentType != null and reDocumentType.trim() != ''">
AND a.re_document_type LIKE '%' + #{reDocumentType} + '%'
</if>
<if test="statusCode != null and statusCode.trim() != ''">
AND a.status_code = #{statusCode}
</if>
<if test="sourceSystem != null and sourceSystem.trim() != ''">
AND a.source_system = #{sourceSystem}
</if>
<if test="targetSystem != null and targetSystem.trim() != ''">
AND a.target_system = #{targetSystem}
</if>
<if test="needRetryFlag != null">
AND a.need_retry_flag = #{needRetryFlag}
</if>
<if test="warehouseId != null and warehouseId.trim() != ''">
AND a.warehouse_id = #{warehouseId}
</if>
<if test="startDate != null and startDate.trim() != ''">
AND CONVERT(varchar(10), a.created_date, 23) &gt;= #{startDate}
</if>
<if test="endDate != null and endDate.trim() != ''">
AND CONVERT(varchar(10), a.created_date, 23) &lt;= #{endDate}
</if>
</where>
ORDER BY a.created_date DESC
<if test="offset != null and limit != null">
OFFSET #{offset} ROWS
FETCH NEXT #{limit} ROWS ONLY
</if>
</select>
<!-- 查询系统日志总数 -->
<select id="queryTotal" resultType="int">
SELECT COUNT(*)
FROM api_log as a
left join api_Interface as b on a.interface_name = b.interface_name AND a.site = b.site
<where>
a.site in (select site from AccessSite where userID = #{userName})
and a.bu_no in (select bu_no from AccessBu where username = #{userName})
and type &lt;&gt; 'Interface'
<if test="interfaceName != null and interfaceName.trim() != ''">
AND a.interface_name LIKE '%' + #{interfaceName} + '%'
</if>
<if test="requestId != null and requestId.trim() != ''">
AND a.request_id = #{requestId}
</if>
<if test="reDocumentNo != null and reDocumentNo.trim() != ''">
AND a.re_document_no LIKE '%' + #{reDocumentNo} + '%'
</if>
<if test="reDocumentType != null and reDocumentType.trim() != ''">
AND a.re_document_type LIKE '%' + #{reDocumentType} + '%'
</if>
<if test="statusCode != null and statusCode.trim() != ''">
AND a.status_code = #{statusCode}
</if>
<if test="sourceSystem != null and sourceSystem.trim() != ''">
AND a.source_system = #{sourceSystem}
</if>
<if test="targetSystem != null and targetSystem.trim() != ''">
AND a.target_system = #{targetSystem}
</if>
<if test="needRetryFlag != null">
AND a.need_retry_flag = #{needRetryFlag}
</if>
<if test="warehouseId != null and warehouseId.trim() != ''">
AND a.warehouse_id = #{warehouseId}
</if>
<if test="startDate != null and startDate.trim() != ''">
AND CONVERT(varchar(10), a.created_date, 23) &gt;= #{startDate}
</if>
<if test="endDate != null and endDate.trim() != ''">
AND CONVERT(varchar(10), a.created_date, 23) &lt;= #{endDate}
</if>
</where>
</select>
<!-- 批量删除 -->
<delete id="deleteBatch">
DELETE FROM api_log WHERE id IN
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<!-- 查询单条api_log记录 -->
<select id="getApiLog" resultType="map">
SELECT
id,
site,
bu_no AS buNo,
request_id AS requestId,
interface_name AS interfaceName,
request_group_id AS requestGroupId,
re_document_no AS reDocumentNo,
re_document_type AS reDocumentType,
order_no AS orderNo,
seq_no AS seqNo,
status_code AS statusCode,
message,
request_data AS requestData,
source_system AS sourceSystem,
target_system AS targetSystem,
need_retry_flag AS needRetryFlag,
retry_count AS retryCount,
max_retry_count AS maxRetryCount,
retry_interval AS retryInterval,
next_retry_time AS nextRetryTime,
last_retry_time AS lastRetryTime,
last_response_data AS lastResponseData,
created_by AS createdBy,
created_date AS createdDate
FROM api_log WITH(NOLOCK)
WHERE site = #{site}
AND bu_no = #{buNo}
AND request_id = #{requestId}
AND request_group_id = #{requestGroupId}
</select>
<!-- 更新接口重试信息 -->
<update id="updateRetryInfo">
UPDATE api_log
SET status_code = #{statusCode},
message = #{message},
last_response_data = #{lastResponseData},
retry_count = #{retryCount},
last_retry_time = GETDATE()
WHERE site = #{site}
AND bu_no = #{buNo}
AND request_id = #{requestId}
AND request_group_id = #{requestGroupId}
</update>
</mapper>
Loading…
Cancel
Save