很多时候项目需要记录每次请求的具体时间、请求的参数等,大多数情况下,很多程序员都是在代码的各个节点,插入一段记录日志的代码,但是这样做非常麻烦,每次写心得代码都要插入这样一段代码。那么有没有什么简单的办法,能记录接口的访问信息和异常信息呢。为了解决这个问题,专门写了一段代码。下面直接上代码。
@Resource private HttpServletRequest request; @AfterReturning(value="execution(* com.nd.sdp.portal.controller.*.*(..))",argNames="returnValue", returning = "returnValue") public void insertLog(JoinPoint point, Object returnValue) { ExceptionRecord exceptionRecord = new ExceptionRecord(); if(ObjectUtils.isNotEmpty(request.getParameterMap())){ Listlist = new ArrayList (); Map params = request.getParameterMap(); for (String key : params.keySet()) { String[] values = params.get(key); for (int i = 0; i < values.length; i++) { String value = values[i]; CustomInterfaceParameter cfp = new CustomInterfaceParameter(); cfp.setParamName(key); cfp.setParamValue(value); list.add(cfp); } } exceptionRecord.setParams(list); }else { List paramList = Arrays.asList(point.getArgs()); if (ObjectUtils.isNotEmpty(paramList)) { int size = paramList.size(); List list = new ArrayList (); for (int i = 0; i < size; i++) { if (ObjectUtils.isNotEmpty(paramList.get(i)) && paramList.get(i).toString().contains("SdpPortalRequest")) { SdpPortalRequest param = new SdpPortalRequest(); param = (SdpPortalRequest) paramList.get(i); CustomInterfaceParameter cfp = new CustomInterfaceParameter(); cfp.setParamName("type"); cfp.setParamValue(param.getType()); list.add(cfp); JSONObject json = param.getParams(); if (ObjectUtils.isNotEmpty(json)) { for (Entry item :json.entrySet()) { CustomInterfaceParameter c = new CustomInterfaceParameter(); c.setParamName(ObjectUtils.isNotEmpty(item.getKey())?item.getKey():""); c.setParamValue(ObjectUtils.isNotEmpty(item.getValue())?item.getValue().toString():""); list.add(c); } } } } exceptionRecord.setParams(list); } } Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (!obj.toString().equals("anonymousUser")) { com.nd.gaea.rest.security.authens.UserInfo userInfo = WafContext.getCurrentUserInfo(); exceptionRecord.setUserId(userInfo.getUserId()); exceptionRecord.setUserName(userInfo.getNickName()); } exceptionRecord.setUrlType(request.getMethod()); exceptionRecord.setExceptionClassName(this.getClass().getName()); exceptionRecord.setRequestMappingName(request.getRequestURI()); exceptionRecord.setType("normalOperation"); exceptionRecord.setIp(Iputil.getIpAddr(request)); exceptionRecord.setCreateTime(Timestamp.valueOf(sdf.format(date))); exceptionRecord.setPlatformName("sdpPortal"); exceptionRecordDao.save(exceptionRecord); }
通过上述代码,我们可以直接从HttpServletRequest和JoinPoint中获取到GET、POST、PUT、DELETE等请求的各种所需要的参数和异常,然后入库,就可以方便的查看访问记录和异常情况。下面是入库信息(MONGO)。
{ "_id" : ObjectId("5a40ad3945ce333894ec3b51"), "exceptionMessage" : "对应环境不存在,appId:5a409ea745ce333894ec3b43,env:1", "exceptionType" : "SdpOperationException: 对应环境不存在,appId:5a409ea745ce333894ec3b43,env:1", "exceptionTypeChinese" : "", "exceptionDetails" : "异常类型: com.nd.component.sdp.portal.service.exception.SdpOperationException: 对应环境不存在,appId:5a409ea745ce333894ec3b43,env:1 com.nd.component.sdp.portal.service.component.environment.model.EnvironmentModel.getEnvironmentEntity(EnvironmentModel.java:103) com.nd.component.sdp.portal.service.component.environment.model.EnvironmentModel.getEnvironmentEntity(EnvironmentModel.java:109) com.nd.component.sdp.portal.service.component.web.elastic.impl.ElasticAdaptV10.getTomcatStatus(ElasticAdaptV10.java:200) com.nd.component.sdp.portal.service.component.web.elastic.ElasticService.getTomcatStatus(ElasticService.java:121) com.nd.component.sdp.portal.service.component.web.WebElasticOperation.doGet(WebElasticOperation.java:86) com.nd.component.sdp.portal.service.component.web.WebElasticOperation$$FastClassBySpringCGLIB$$81e31e0b.invoke() org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) com.nd.component.sdp.portal.service.component.web.WebElasticOperation$$EnhancerBySpringCGLIB$$c0ba16cd.doGet( ) com.nd.component.sdp.portal.service.excutor.GetExcutor.doGet(GetExcutor.java:45) com.nd.sdp.portal.service.GetService.get(GetService.java:23) com.nd.sdp.portal.controller.ApplicationResourceController.getTomcatState(ApplicationResourceController.java:159) com.nd.sdp.portal.controller.ApplicationResourceController$$FastClassBySpringCGLIB$$c4ef8b30.invoke( ) org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) com.nd.sdp.portal.controller.ApplicationResourceController$$EnhancerBySpringCGLIB$$b4b4259b.getTomcatState( ) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:606) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:747) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:676) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) javax.servlet.http.HttpServlet.service(HttpServlet.java:624) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) com.nd.gaea.rest.filter.TokenAuthenticationProcessFilter.doFilterInternal(TokenAuthenticationProcessFilter.java:91) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) com.nd.gaea.rest.filter.WafHttpMethodOverrideFilter.doFilterInternal(WafHttpMethodOverrideFilter.java:70) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) com.nd.gaea.rest.filter.WafCorsFilter.doFilterInternal(WafCorsFilter.java:43) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) com.nd.gaea.rest.filter.ExceptionFilter.doFilterInternal(ExceptionFilter.java:66) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1706) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) ", "urlType" : "GET", "type" : "exceptionOperation", "exceptionClassName" : "com.nd.sdp.portal.exception.CustomExceptionHandler", "exceptionLocation" : "com.nd.component.sdp.portal.service.component.environment.model.EnvironmentModel.getEnvironmentEntity(EnvironmentModel.java:103)", "requestMappingName" : "/v0.2/app/5a409ea745ce333894ec3b43/resources/state", "userId" : "339691", "userName" : "", "ip" : "192.168.252.29", "createTime" : ISODate("2017-12-25T07:48:09.000Z"), "params" : [ { "paramName" : "env", "paramValue" : "1" }, { "paramName" : "type", "paramValue" : "ELASTIC_OPERATION" } ], "platformName" : "sdpPortal"}
上述代码由于使用AOP的方式进行记录,故要注意性能问题,很多接口并不需要进行记录。所以一定要注意,建议可以采用自定义注解的形式编写代码,在需要记录的接口上写上注解就可以了。