本文主要通过java Aop面向切面的思想进行访问程序的监控,话不多说,先上代码。
1.导入包:
<dependency>
<groupId></groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
2.定义切面代码:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* 用来处理异常信息的切面
*
* @author root
*/
@Component
@Aspect
@Slf4j
public class ExceptionAop {
@ApolloConfig
private Config config;
@Autowired
private EmailUtil emailUtil;
@Around("execution(* ..*.*(..))")//这里可以通过你的项目包名进行配置
public Object around(ProceedingJoinPoint pj) throws Throwable {
long starttime=();
try {
("---------------------API请求参数:【"+getMessage(pj, null)+ "】");
Object obj = ();
long size = (obj);
if(size<2*1024){
//2kb
("---------------------API返回值:【" +"类名:{},方法名:{};返回值:{}】",().getClass().getSimpleName(),().getName(),(obj));
}
return obj;
} catch (MethodArgumentNotValidException e) {
().getGlobalErrors();
return ("请求参数验证失败");
} catch (SocketTimeoutException e) {
concatError(starttime, getMessage(pj, e));
return (MybConstants.EXCEPTION_TIMEOUT_ERROR);
} catch (Exception e) {
concatError(starttime, getMessage(pj, e));
return (MybConstants.EXCEPTION_BUSY);
}
}
private void concatError(long starttime, String message) {
StringBuilder stringBuilder=new StringBuilder( "<h3>接口耗时:</h3>");
("接口花费时间:").append(()-starttime).append("ms<br/>");
(message);
sendErrorNotice(());
}
private String getMessage(ProceedingJoinPoint pj, Exception e) {
if (e != null) {
((), e);
}
RequestAttributes ra = ();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = ();
String token = ();
String userInfo = (MybConstants.HEAD_USER_INFO);
StringBuilder joiner = new StringBuilder("<h3>链接:</h3>")
.append(())
.append("<br/><h3>token:</h3>")
.append((token == null ? "" : token))
.append("<br/><h3>user phone info:</h3>")
.append((userInfo == null ? "" : userInfo))
.append(";<br/><h3>类名:</h3>")
.append(().getClass().getSimpleName())
.append(";<br/><h3>方法:</h3>")
.append(().getName())
.append(";<br/><h3>参数:</h3>");
Object[] args = ();
List<Object> objects=new ArrayList<>();
for(Object object:args){
if(object instanceof MultipartFile || object instanceof File ){
continue;
}
(object);
}
((objects));
if ((e)) {
joiner .append(";<br/><h3>message:</h3>")
.append(())
.append(";<br/><h3>异常:</h3>")
.append((e));
}
return ();
}
private void sendErrorNotice(String content) {
(content);
boolean enable = ("", false);
if (enable) {
(content);//发送邮件,具体邮件配置可以参考我的资源中的邮件发送 源码
}
}
}