輸入com.google.gson.Gson。
輸入lombok.extern.slf4j.Slf4j。
輸入org.aspectj.lang.JoinPoint。
輸入org.aspectj.lang.ProceedingJoinPoint。
輸入org.aspectj.lang.annotation.Around;
輸入org.aspectj.lang.annotation.Aspect;
輸入org.aspectj.lang.annotation.Before;
輸入org.aspectj.lang.annotation.Pointcut;
輸入org.springframework.context.annotation.Configuration。
輸入org.springframework.http.ResponseEntity。
輸入org.springframework.web.context.request.RequestContextHolder。
インポートorg.springframework.web.context.request.ServletRequestAttributes;
インポートのjavax.servlet.http.HttpServletRequest;
輸入java.lang.reflect.Methodオブジェクト。
輸入java.util.Objects。
@Aspect
@Configuration
@ SLF4J
パブリック クラスWebLogAspect {
/ **
*以自定义@WebLog注解为切点
* /
@Pointcut( "@Annotation(com.experiencetex.skills.config.annotation.WebLog)" )
公共 無効ウェブログ( ){
}
/ **
*环绕
*
* @return java.lang.Object上位
* @params [PJP]
* @description
* /
@Around( "ウェブログ()" )
パブリックオブジェクトdoAround(ProceedingJoinPoint PJP)がスローされたThrowableを{
長いのstartTime = にSystem.currentTimeMillis();
オブジェクトの結果 = pjp.proceed()。
もし(!(結果のinstanceof ResponseEntity)){
log.info( "応答のArgs:{}"、新しい。)Gson(toJson(結果));
log.info( "時間がかかる:{}"のSystem.currentTimeMillis() - のstartTime)。
}
戻り値の結果;
}
/ **
*在切点之前记录
*
* @Return ボイド
* @params [ジョインポイント]
* @description
* /
@Before( "ウェブログ()" )
公共 ボイド doBefore(ジョインポイントジョインポイント)がスロー{例外を
// 印刷要求ログ開始
ServletRequestAttributesする属性が= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes( );
HttpServletRequestのリクエスト = Objects.requireNonNull(属性).getRequest();
// 注釈@WebLogの説明取得
ストリングmethodDescription = getAspectLogDescription(ジョインポイントを);
// 印刷要求パラメータ
log.info(「========================================スタート==== ====================================== " );
// 印刷要求URLの
log.info( "URL:{}" 、request.getRequestURL()のtoString());.
// 印刷記述
log.info( "説明:{}" 、methodDescription);
// 印刷方法のHttp
log.info(「方法、HTTP: } { "request.getMethod());
// コールコントローラとのフルパス行う印刷方法
log.info("クラス方法:{} {}」を、joinPoint.getSignature()getDeclaringTypeName()、joinPoint.getSignature。 ().getName());
// 印刷要求IP
log.info( "IP:{}" 、request.getRemoteAddr());
// 基準に印刷要求
log.info( "Argsの要求:{}"、新しい新Gson()toJson(joinPoint.getArgs()))。 ;
}
/ **
*記述部注釈を取得する
*
* @param ジョインポイント接点
* @returnの説明
* @throws 例外
* /
パブリック文字列getAspectLogDescription(ジョインポイントジョインポイント)を
スロー例外{
文字列ターゲット名 = joinPoint.getTarget()はgetClassが(。 ).getName();
文字列methodNameの =。joinPoint.getSignature()のgetName();
[]引数オブジェクト =用)(joinPoint.getArgs。
クラスtargetClass = Class.forNameの(ターゲット名)。
方法[]メソッド = targetClass.getMethods()。
StringBuilderの説明 = 新規のStringBuilder();
用(方法方法:方法){
場合(method.getName()に等しい(methodNameの)){
クラス[] clazzsの =のmethod.getParameterTypes()。
もし(clazzs.length == arguments.lengthを){
description.append(method.getAnnotation(ウェブログ。クラス).DESCRIPTION());
破ります;
}
}
}
戻りdescription.toStringを();
}
}