package cc.cloud.log;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LogRecord {
String title() default"";
String action() default"";
}
package cc.cloud.log;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component("logAspect")
public class LogAspect {
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
// 配置織入點
@Pointcut("@annotation(cc.cloud.log.LogRecord)")
public void logPointCut() {
}
/**
* 前置通知 用于攔截操作,在方法傳回後執行
* @param joinPoint 切點
*/
@AfterReturning(pointcut = "logPointCut()")
public void doBefore(JoinPoint joinPoint) {
handleLog(joinPoint, null);
}
/**
* 攔截異常操作,有異常時執行
*
* @param joinPoint
* @param e
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfter(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e);
}
private void handleLog(JoinPoint joinPoint, Exception e) {
try {
// 獲得注解
LogRecord controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
// 獲得方法名稱
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
String action = controllerLog.action();
String title = controllerLog.title();
//列印日志,如有需要還可以存入資料庫
log.info("子產品名稱:{}",title);
log.info("操作名稱:{}",action);
log.info("類名:{}",className);
log.info("方法名:{}",methodName);
} catch (Exception exp) {
// 記錄本地異常日志
log.error("==前置通知異常==");
log.error("異常資訊:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 是否存在注解,如果存在就擷取
*/
private static LogRecord getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(LogRecord.class);
}
return null;
}
}
@RequestMapping("examList")
@ResponseBody
@LogRecord(title="考試清單",action="擷取考試清單")
public ExamsVO examList(HttpServletRequest request, String keyword, String termId) {
.
.
.
}