diff --git a/README.md b/README.md index 88b1ab4..21c86b7 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ crud操作demo | ✔ 集成监控功能 | ✔ 包结构调整 | ✔ SpringSecurity登录改为Restful形式 | -SpringAOP通用日志处理 | +SpringAOP通用日志处理 | ✔ ### 功能完善 diff --git a/mall-admin/src/main/java/com/macro/mall/bo/WebLog.java b/mall-admin/src/main/java/com/macro/mall/bo/WebLog.java new file mode 100644 index 0000000..cec4fbb --- /dev/null +++ b/mall-admin/src/main/java/com/macro/mall/bo/WebLog.java @@ -0,0 +1,143 @@ +package com.macro.mall.bo; + +/** + * Controller层的日志封装类 + */ +public class WebLog { + /** + * 操作描述 + */ + private String description; + + /** + * 操作用户 + */ + private String username; + + /** + * 操作时间 + */ + private Long startTime; + + /** + * 消耗时间 + */ + private Integer spendTime; + + /** + * 根路径 + */ + private String basePath; + + /** + * URI + */ + private String uri; + + /** + * URL + */ + private String url; + + /** + * 请求类型 + */ + private String method; + + /** + * IP地址 + */ + private String ip; + + private Object parameter; + + private Object result; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Long getStartTime() { + return startTime; + } + + public void setStartTime(Long startTime) { + this.startTime = startTime; + } + + public Integer getSpendTime() { + return spendTime; + } + + public void setSpendTime(Integer spendTime) { + this.spendTime = spendTime; + } + + public String getBasePath() { + return basePath; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public Object getParameter() { + return parameter; + } + + public void setParameter(Object parameter) { + this.parameter = parameter; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } +} diff --git a/mall-admin/src/main/java/com/macro/mall/component/WebLogAspect.java b/mall-admin/src/main/java/com/macro/mall/component/WebLogAspect.java index 1110271..2598be1 100644 --- a/mall-admin/src/main/java/com/macro/mall/component/WebLogAspect.java +++ b/mall-admin/src/main/java/com/macro/mall/component/WebLogAspect.java @@ -1,18 +1,30 @@ package com.macro.mall.component; +import com.macro.mall.bo.WebLog; +import com.macro.mall.util.JsonUtils; +import com.macro.mall.util.RequestUtil; +import io.swagger.annotations.ApiOperation; import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.*; +import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.*; /** * 统一日志处理切面 @@ -30,19 +42,69 @@ public class WebLogAspect { @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); - //获取当前请求对象 - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletRequest request = attributes.getRequest(); - //记录请求信息(可以记录到数据库中) - String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); - String args = Arrays.toString(joinPoint.getArgs()); - LOGGER.info("HTTP URL:{}; HTTP_METHOD:{}; IP:{}; CLASS_METHOD:{}; ARGS:{}", - request.getRequestURL(), request.getMethod(), request.getRemoteAddr(), classMethod, args); } @AfterReturning(value = "webLog()", returning = "ret") public void doAfterReturning(Object ret) throws Throwable { - long costTime = System.currentTimeMillis() - startTime.get(); - LOGGER.info("RESPONSE:{}; COST_TIME:{}ms", ret, costTime); + } + + @Around("webLog()") + public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { + //获取当前请求对象 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + //记录请求信息(可以记录到数据库中) + WebLog webLog = new WebLog(); + Object result = joinPoint.proceed(); + Signature signature = joinPoint.getSignature(); + MethodSignature methodSignature = (MethodSignature) signature; + Method method = methodSignature.getMethod(); + if (method.isAnnotationPresent(ApiOperation.class)) { + ApiOperation log = method.getAnnotation(ApiOperation.class); + webLog.setDescription(log.value()); + } + long endTime = System.currentTimeMillis(); + webLog.setBasePath(RequestUtil.getBasePath(request)); + webLog.setIp(request.getRemoteUser()); + webLog.setMethod(request.getMethod()); + webLog.setParameter(getParameter(method, joinPoint.getArgs())); + webLog.setResult(result); + webLog.setSpendTime((int) (endTime - startTime.get())); + webLog.setStartTime(startTime.get()); + webLog.setUri(request.getRequestURI()); + webLog.setUrl(request.getRequestURL().toString()); + LOGGER.info("{}", JsonUtils.objectToJson(webLog)); + return result; + } + + /** + * 根据方法和传入的参数获取请求参数 + */ + private Object getParameter(Method method, Object[] args) { + List argList = new ArrayList<>(); + Parameter[] parameters = method.getParameters(); + for (int i = 0; i < parameters.length; i++) { + RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class); + if (requestBody != null) { + argList.add(args[i]); + } + RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class); + if (requestParam != null) { + Map map = new HashMap<>(); + String key = parameters[i].getName(); + if (!StringUtils.isEmpty(requestParam.value())) { + key = requestParam.value(); + } + map.put(key, args[i]); + argList.add(map); + } + } + if (argList.size() == 0) { + return null; + } else if (argList.size() == 1) { + return argList.get(0); + } else { + return argList; + } } } diff --git a/mall-admin/src/main/java/com/macro/mall/controller/PmsBrandController.java b/mall-admin/src/main/java/com/macro/mall/controller/PmsBrandController.java index 7b0b6fa..e33c73d 100644 --- a/mall-admin/src/main/java/com/macro/mall/controller/PmsBrandController.java +++ b/mall-admin/src/main/java/com/macro/mall/controller/PmsBrandController.java @@ -28,21 +28,21 @@ public class PmsBrandController { @ApiOperation(value = "获取全部品牌列表") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody - public Object getBrandList() { + public Object getList() { return new CommonResult().success(brandService.listAllBrand()); } @ApiOperation(value = "添加品牌") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody - public Object createBrand(@Validated @RequestBody PmsBrandParam pmsBrand, BindingResult result) { + public Object create(@Validated @RequestBody PmsBrandParam pmsBrand, BindingResult result) { if (result.hasErrors()) { return new CommonResult().validateFailed(result.getFieldError().getDefaultMessage()); } CommonResult commonResult; int count = brandService.createBrand(pmsBrand); if (count == 1) { - commonResult = new CommonResult().success(pmsBrand); + commonResult = new CommonResult().success(count); } else { commonResult = new CommonResult().failed(); } @@ -59,7 +59,7 @@ public class PmsBrandController { CommonResult commonResult; int count = brandService.updateBrand(id, pmsBrandParam); if (count == 1) { - commonResult = new CommonResult().success(pmsBrandParam); + commonResult = new CommonResult().success(count); } else { commonResult = new CommonResult().failed(); } @@ -69,7 +69,7 @@ public class PmsBrandController { @ApiOperation(value = "删除品牌") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody - public Object deleteBrand(@PathVariable("id") Long id) { + public Object delete(@PathVariable("id") Long id) { int count = brandService.deleteBrand(id); if (count == 1) { return new CommonResult().success(null); @@ -81,7 +81,7 @@ public class PmsBrandController { @ApiOperation(value = "根据品牌名称分页获取品牌列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody - public Object listBrand(@RequestParam(value = "keyword", required = false) String keyword, + public Object getList(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { return new CommonResult().pageSuccess(brandService.listBrand(keyword, pageNum, pageSize)); @@ -90,14 +90,14 @@ public class PmsBrandController { @ApiOperation(value = "根据编号查询品牌信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody - public Object getBrand(@PathVariable("id") Long id) { + public Object getItem(@PathVariable("id") Long id) { return new CommonResult().success(brandService.getBrand(id)); } @ApiOperation(value = "批量删除品牌") @RequestMapping(value = "/delete/batch", method = RequestMethod.POST) @ResponseBody - public Object deleteBrandBatch(@RequestParam("ids") List ids) { + public Object deleteBatch(@RequestParam("ids") List ids) { int count = brandService.deleteBrand(ids); if (count > 0) { return new CommonResult().success(count); diff --git a/mall-admin/src/main/java/com/macro/mall/util/RequestUtil.java b/mall-admin/src/main/java/com/macro/mall/util/RequestUtil.java new file mode 100644 index 0000000..3e625e0 --- /dev/null +++ b/mall-admin/src/main/java/com/macro/mall/util/RequestUtil.java @@ -0,0 +1,67 @@ +package com.macro.mall.util; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * request工具类 + */ +public class RequestUtil { + + /** + * 移除request指定参数 + */ + public String removeParam(HttpServletRequest request, String paramName) { + String queryString = ""; + Enumeration keys = request.getParameterNames(); + while (keys.hasMoreElements()) { + String key = (String) keys.nextElement(); + if (key.equals(paramName)) { + continue; + } + if ("".equals(queryString)) { + queryString = key + "=" + request.getParameter(key); + } else { + queryString += "&" + key + "=" + request.getParameter(key); + } + } + return queryString; + } + + /** + * 获取请求basePath + */ + public static String getBasePath(HttpServletRequest request) { + StringBuffer basePath = new StringBuffer(); + String scheme = request.getScheme(); + String domain = request.getServerName(); + int port = request.getServerPort(); + basePath.append(scheme); + basePath.append("://"); + basePath.append(domain); + if("http".equalsIgnoreCase(scheme) && 80 != port) { + basePath.append(":").append(String.valueOf(port)); + } else if("https".equalsIgnoreCase(scheme) && port != 443) { + basePath.append(":").append(String.valueOf(port)); + } + return basePath.toString(); + } + + /** + * 请求中参数转Map,for支付宝异步回调,平时建议直接使用request.getParameterMap(),返回Map + */ + public static Map getParameterMap(HttpServletRequest request) { + Map result = new HashMap<>(); + Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String parameterName = (String) parameterNames.nextElement(); + result.put(parameterName, request.getParameter(parameterName)); + } + return result; + } + +}