赞
踩
日志的重要性不多说了,为了时候追溯和排错,我们在数据库中保存了接口服务调用请求与响应的完整数据,并且为了方便地做性能分析,把每次接口调用从收到请求到返回响应的时间差也保存了下来,这一点,在实际工作中非常重要,可以做预警和预判,在接口缓慢或崩溃前发现问题。
无论接口调用的结果是成功还是失败,正常还是异常,我们都希望把日志完整地记录下来,因此,对于日志的处理,并不是通过过滤器实现的,而是放到了异常处理的finally块中。
/**
* '
* API服务技术框架实现
*
* @author wqliu
* @date 2022-2-10 14:44
**/
@Service
public class ApiRestServiceImpl implements ApiRestService {
private ApiFilterChain filterChain;
@Autowired
private ApiServiceLogService apiServiceLogService;
public ApiRestServiceImpl(FrameworkValidateFilter frameworkValidateFilter,
BusinessFilter businessFilter, BasicValidateFilter basicValidateFilter) {
filterChain=new ApiFilterChain(basicValidateFilter,frameworkValidateFilter,businessFilter);
}
@Override
public ApiResponse handle(ApiRequest apiRequest) {
LocalDateTime receiveTime = LocalDateTime.now();
ApiResponse apiResponse = new ApiResponse();
try {
filterChain.doFilter(apiRequest,apiResponse);
apiResponse = this.filterChain.getResponse();
apiResponse.setExecuteResult(ApiServiceExecuteResultEnum.SUCCESS.name());
} catch (CustomException ex) {
//自定义异常处理
apiResponse.setExecuteResult(ApiServiceExecuteResultEnum.ERROR.name());
apiResponse.setErrorCode("S00");
apiResponse.setErrorMessage(ex.getMessage());
} catch (ApiException ex) {
//API异常处理
apiResponse.setExecuteResult(ApiServiceExecuteResultEnum.ERROR.name());
apiResponse.setErrorCode(ex.getErrorCode());
apiResponse.setErrorMessage(ex.getMessage());
} catch (Exception ex) {
//非预期异常处理
apiResponse.setExecuteResult(ApiServiceExecuteResultEnum.ERROR.name());
apiResponse.setErrorCode("S99");
apiResponse.setErrorMessage("未定义异常:" + ex.getMessage());
} finally {
//需要重置,为下次请求服务
filterChain.reset();
//记录日志
apiServiceLogService.recordLog(apiRequest,apiResponse,receiveTime);
}
return apiResponse;
}
}
日志保存如下:
@Override
public void recordLog(ApiRequest request, ApiResponse response, LocalDateTime receiveTime) {
LocalDateTime responseTime = LocalDateTime.now();
ApiServiceLog apiServiceLog = new ApiServiceLog();
apiServiceLog.setAppCode(request.getAppCode());
apiServiceLog.setServiceCode(request.getServiceCode());
apiServiceLog.setRequestTime(DateUtils.toLocalDateTime(request.getRequestTime()));
apiServiceLog.setReceiveTime(receiveTime);
apiServiceLog.setRequestBusinessData(request.getData());
apiServiceLog.setExecuteResult(response.getExecuteResult());
apiServiceLog.setErrorCode(response.getErrorCode());
apiServiceLog.setErrorMessage(response.getErrorMessage());
apiServiceLog.setResponseTime(responseTime);
apiServiceLog.setResponseBusinessData(response.getData());
//计算执行时间
apiServiceLog.setExecutionTime(Duration.between(receiveTime, responseTime).toMillis());
//保存
add(apiServiceLog);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。