使用spring的aop做簡單系統日誌,可以記錄ip

 

系統日誌一般就是記錄操作系統的操作人,操作哪些功能,用戶的ip等;就可以利用aop切service層的方法。這裏我用的是環繞通知,相對而言比較簡單。

在這裏我用的是全註解模式,在xml中開啓支持aop

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Component
@Aspect
public class LogAdvice {
    @Autowired
    private HttpServletRequestUtil httpUtils;
    @Autowired
    private SystemLogMapper systemLogMapper;

    @Around(value = "execution(* cn.itsource.crm.service.I*Service.*(..)) || execution(* cn.itsource.base.service.I*Service.*(..))")
    public Object  myArround(ProceedingJoinPoint p) throws Throwable{
        SystemLog systemLog= new SystemLog();

        User user = UserContext.getUser();
        systemLog.setOpUser(user.getName());

        String remoteAddr = httpUtils.getRequest().getRemoteAddr();//IP
        systemLog.setOpIp(remoteAddr);

        Signature signature = p.getSignature(); //方法簽名
        String string = signature.toString();
        systemLog.setFunction(string);

        //[cn.itsource.crm.query.RepairOrderQuery@1c37e537]
        Object[] args = p.getArgs();
        String string2 = args.toString();
        System.out.println(string2+"111111111111111111111111");
        List<Object> objects = Arrays.asList(p.getArgs());//參遞的參數
        String string1 = objects.toString();
        if(string1.length()>200){
            string1 = string1.substring(0,200);
        }
        systemLog.setParams(string1);

        systemLog.setOpTime(new Date()); //當前時間

        systemLogMapper.save(systemLog);//保存日誌信息

        Object result = p.proceed();//放行

        return result;

    }

}

通過攔截器來獲取HttpServletRequest對象;其中寫了個工具類來保存HttpServletRequest對象。

/**
 * 攔截器  攔截controller層所有的請求
 * 作用:獲取到request對象
 */
public class GetRequestFilter extends HandlerInterceptorAdapter {

    @Autowired
    private HttpServletRequestUtil httpUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        httpUtils.setRequest(request);
        return super.preHandle(request, response, handler);
    }
}

@Component
public class HttpServletRequestUtil {
    private HttpServletRequest request;

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
}

 

 

 

發佈了70 篇原創文章 · 獲贊 3 · 訪問量 5741
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章