天天看點

從零開始搭建自己的網站二十四:使用注解記錄記錄檔

對于一個網站來說肯定需要記錄記錄檔,比如在幾點幾分,進行了登入,幾點幾分删除了一篇文章等這些記錄檔。

我們使用AOP+注解的方式來進行記錄記錄檔。

在下面的代碼中,需要注意的就是方法上注解要寫在第一行。

/**
 * 操作前日志,用于登出,擷取使用者名和ID
 */
@Target(value = {ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLogBefore {

    /**
     * 操作類型,必填
     */
    String action();

    /**
     * 操作的子產品
     */
    String module() default "";

}
           
@Target(value = {ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {

    /**
     * 操作類型,必填
     */
    String action();

    /**
     * 操作的子產品
     */
    String module() default "";

}
           
/**
 * 切面類
 */
@Aspect
@Component
public class SystemLogAspect {

    private static final Logger logger = Logger.getLogger(SystemLogAspect.class);

    @Autowired
    private LogInfoDao logInfoDao;

    /**
     * Service層切點
     */
    @Pointcut("@annotation(com.dyw.utils.log.SystemServiceLog)")
    public void serviceAspect() {

    }

    /**
     * Service層切點
     */
    @Pointcut("@annotation(com.dyw.utils.log.SystemServiceLogBefore)")
    public void serviceAspectBefore() {

    }

    /**
     * 擷取注解參數,記錄日志
     *
     * @param joinPoint 切入點參數
     */

    @After("serviceAspect()")
    public void doServiceLog(JoinPoint joinPoint) {
        createLog(joinPoint);
    }

    @Before("serviceAspectBefore()")
    public void serviceAspectBefore(JoinPoint joinPoint) {
        createLog(joinPoint);
    }

    /**
     * 擷取 操作指令
     */
    private String getMethodActionAndModule(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String action = "";
        String module = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    Annotation[] annotations = method.getAnnotations();
                    try{
                        //用annotations[0],使用注解的時候必須把注解放在第一行
                        SystemServiceLog systemServiceLog = (SystemServiceLog) annotations[0];
                        action = systemServiceLog.action();
                        module = systemServiceLog.module();
                    }catch (Exception e){
                        SystemServiceLogBefore systemServiceLog = (SystemServiceLogBefore) annotations[0];
                        action = systemServiceLog.action();
                        module = systemServiceLog.module();
                    }
                }
            }
        }
        if(StringUtils.isNotBlank(module)){
            return action + "-" + module;
        }
        return action;
    }

    private void createLog(JoinPoint joinPoint) {
        logger.info("日志記錄");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        LogInfo logInfo = new LogInfo();
        try {
            //擷取操作行為及操作子產品
            String am = getMethodActionAndModule(joinPoint);
            logInfo.setOperate(am);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        User user = (User) request.getSession().getAttribute("user");
        //操作時間
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String operateTime = sdf.format(new Date());
        //判斷是pc端還是手機
        String equipment;
        String userAgent = request.getHeader("User-Agent");
        boolean pcFlag = userAgent != null && (userAgent.toUpperCase().contains("WINDOWS") || userAgent.toUpperCase().contains("MACINTOSH"));
        if (pcFlag) {
            //pc端
            equipment = "pc";
        } else {
            equipment = "mobile";
        }
        if (user != null) {
            logInfo.setUserid(String.valueOf(user.getId()));
            logInfo.setUsername(user.getUsername());
        }
        logInfo.setIPAddress(IPUtils.getRemoteIp(request));
        logInfo.setOperatetime(operateTime);
        logInfo.setDevice(equipment);
        logInfoDao.addLogInfo(logInfo);
    }
}
           
/**
 * 操作常量
 */
public class ActionConstants {

    public static final String LOGIN = "登入";

    public static final String LOGOUT = "登出";

    public static final String INSERT = "新增操作";

    public static final String UPDATE = "更新操作";

    public static final String DELETE = "删除操作";

    public static final String UPLOAD = "上傳檔案";

    public static final String HANDLE = "辦理";
}
/**
 * 子產品常量
 */
public class ModuleConstants {

    public static final String USER = "使用者";
    public static final String ARTICLE = "文章";
    public static final String CATEGORY = "類别";
    public static final String KEYWORD = "關鍵字";

}
           
/**
 * 登入使用者
 */
@SystemServiceLog(action = ActionConstants.LOGIN)
@RequestMapping("/loginUser")
@ResponseBody
public String loginUser(HttpServletRequest request, String username, String password) {
    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        User login = userService.login(username, password);
        if (login != null) {
            request.getSession().setAttribute("user", login);
            return "success";
        }
    }
    return "fail";
}

/**
 * 登出登入
 */
@SystemServiceLogBefore(action = ActionConstants.LOGOUT)
@RequestMapping("/outLogin")
public String outLogin(HttpServletRequest request) {
    request.getSession().setAttribute("user", null);
    return "redirect:/login/login";
}
           

歡迎轉載,轉載請注明出處 http://www.dingyinwu.com/article/69.html

如果文章中有任何問題或者可以改進的地方,請大家多提提意見,我會非常感激。

繼續閱讀