通過aop添加日志管理


1.使用spring 的 aop 技術切到自定義注解上,所以先創建一個自定義注解類

import java.lang.annotation.*;

@Target(ElementType.METHOD) //注解放置的目標位置,METHOD是可注解在方法級別上
@Retention(RetentionPolicy.RUNTIME) //注解在哪個階段執行
@Documented //生成文檔
public @interface MyLog {
    String value()  default "";//功能模塊名稱
    int type() default 1;//用戶具體操作類型代表,0:登錄;1:查詢;2:新增;3:修改;import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.util.Map; /** * 系統日志:切面處理類 */ @Aspect @Component public class SysLogAspect { @Resource private IViapLogInfoService viapLogInfoService; //定義切點 @Pointcut //在注解的位置切入代碼 @Pointcut("@annotation( com.harzone.lhps.viap.interceptor.MyLog)") public void logPoinCut() { } //切面 配置通知 @AfterReturning("logPoinCut()") public void saveSysLog(JoinPoint joinPoint) { try { ViapLogInfo viapLogInfo = new ViapLogInfo();
        //獲取request RequestAttributes ra
= RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest();
        //獲取客戶端ip viapLogInfo.setIp(WebUtil.getHost(request));
//保存日志 //從切面織入點處通過反射機制獲取織入點處的方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //獲取切入點所在的方法 Method method = signature.getMethod(); //獲取請求的類名 // String className = joinPoint.getTarget().getClass().getName(); //獲取請求的方法名 // String methodName = method.getName(); //請求的參數 // Object[] args = joinPoint.getArgs(); //獲取request中的json字符串 JSONObject obj=GetRequestJsonUtils.getRequestJsonObject(request); // String params = JSON.toJSONString(obj); //獲取操作 MyLog myLog = method.getAnnotation(MyLog.class); if (myLog != null) { if(obj != null) { JSONObject jo = new JSONObject(); if (myLog.status() == 1) { // viapLogInfo.setOperateCondition(className + "." + params); for (Map.Entry<String, Object> entry : obj.entrySet()) { if(entry.getValue() != null && !"".equals(entry.getValue())) { jo.put(entry.getKey(),entry.getValue()); } } } viapLogInfo.setOperateCondition(jo.toString()); } viapLogInfo.setValue(myLog.value()); } viapLogInfoService.add(viapLogInfo); } catch (Exception e) { e.printStackTrace(); } }

3.接下來就可以在需要監控的方法上添加 aop的自定義注解格式為 @+自定義注解的類名 @MyLog

  @PostMapping("login.json")
    @MyLog(value= "登錄"")
    public JSONObject login(@RequestBody User userser) {
        
        return null;
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM