欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

项目操作日志记录(方法级别)

程序员文章站 2022-03-11 21:33:37
...
在项目中要记录操作日志,可以通过spring的Aop技术去实现,下面是自己在项目是上面的应用,记录下。
1、在Controller层有方法执行前记录和方法执行后记录,定义2个注解类
package com.winning.common.systemlog;

import java.lang.annotation.*;

/**  
 *自定义注解 拦截Controller
 * 在进入Controller之前进行拦截
 */    
    
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLogAfterController {
	
	String description()  default "";

	String czmk() default "";
}



package com.winning.common.systemlog;

import java.lang.annotation.*;

/**  
 *自定义注解 拦截Controller
 * 在进入Controller后拦截
 */    
    
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLogBeforeController {
	
	String description()  default "";

	String czmk() default  "";
}


在service记录异常日志信息
package com.winning.common.systemlog;

import java.lang.annotation.*;


/**
 * 拦截Service进行异常日志记录
 * @author TonyJ
 *
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLogService {
	String description()  default "";
	String czmk() default  "";
}


2、定义日志的切面类
package com.winning.common.systemlog;

import com.alibaba.fastjson.JSON;
import com.winning.common.constant.Constants;
import com.winning.common.entitys.system.LoginUser;
import com.winning.common.entitys.system.SysLog;
import com.winning.common.service.SysCzrzService;
import com.winning.common.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class SystemLogAspect {

	@Autowired
	private SysCzrzService sysCzrzService;

	// 本地异常日志记录对象
	private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

	// Controller层切点 之前
	@Pointcut("@annotation(com.winning.common.systemlog.SystemLogBeforeController)")
	public void controllerBeforeAspect() {
	}
	
	// Controller层切点 之后
	@Pointcut("@annotation(com.winning.common.systemlog.SystemLogAfterController)")
	public void controllerAfterAspect() {
	}
	
	//service层切点
	@Pointcut("@annotation(com.winning.common.systemlog.SystemLogService)")
	public void serviceAspect(){
		
	}
	
	/**  
     * 异常通知 用于拦截service层记录异常日志  
     *  
     * @param joinPoint  
     * @param e  
     */    
     @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
     public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String uri = request.getRequestURI();
		 // 读取session中的用户
		 LoginUser loginUser = ShiroUtils.getLoginUser();
		 // 请求的IP
		 String ip = ShiroUtils.getIp();
        String params = "";
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {    
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {    
                params += JSON.toJSONString(joinPoint.getArgs()[i]) + ";";
            }    
        }    
         try {
         	/*==========数据库日志=========*/
            SysLog log = new SysLog();
            log.setCznr(getServiceMthodDescription(joinPoint).get("description"));
           	log.setRzlx("2");
           	log.setCzsj(new Date());
           	log.setCzr(loginUser.getId()+"");
           	log.setIpdz(ip);
           	log.setQqdz(uri);
           	log.setJgbm(loginUser.getJgbm());
           	log.setYcxx("异常code:"+e.getClass().getName()+",异常详情:"+e.getMessage());
           	log.setDmxx((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+",params:"+params);
            //保存数据库
			 sysCzrzService.saveLog(log);

        }  catch (Exception ex) {
            //记录本地异常日志    
            logger.error("==异常通知异常==");    
            logger.error("异常信息:{}", ex.getMessage());    
        }    
         /*==========记录本地异常日志==========*/    
        logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);    
    
    }    
	
	@After("controllerAfterAspect()")
	public void doAfter(JoinPoint joinPoint){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String uri = request.getRequestURI();
		// 读取session中的用户
		LoginUser loginUser = ShiroUtils.getLoginUser();
		// 请求的IP
		String ip = ShiroUtils.getIp();

		try {
			// *========数据库日志=========*//
			SysLog log = new SysLog();
			log.setCznr(getAfterControllerMethodDescription(joinPoint).get("description"));
			log.setCzmk(getAfterControllerMethodDescription(joinPoint).get("czmk"));
			log.setRzlx("1");
			log.setCzsj(new Date());
			log.setCzr(loginUser.getId()+"");
			log.setIpdz(ip);
			log.setQqdz(uri);
			log.setJgbm(loginUser.getJgbm());
			log.setDmxx((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
			// 保存数据库
			sysCzrzService.saveLog(log);

		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==后置通知异常==");
			logger.error("异常信息:{}", e.getMessage());
		}
	}

	/**
	 * 前置通知 用于拦截Controller层记录用户的操作
	 * @param joinPoint
	 *            切点
	 */
	@Before("controllerBeforeAspect()")
	public void doBefore(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String uri = request.getRequestURI();
		// 读取session中的用户
		LoginUser loginUser = ShiroUtils.getLoginUser();
		// 请求的IP
		String ip = ShiroUtils.getIp();

		try {
			// *========数据库日志=========*//
			SysLog log = new SysLog();
			log.setCznr(getBeforeControllerMethodDescription(joinPoint).get("description"));
			log.setCzmk(getBeforeControllerMethodDescription(joinPoint).get("czmk"));
			log.setRzlx("1");
			log.setCzsj(new Date());
			log.setCzr(loginUser.getId()+"");
			log.setIpdz(ip);
			log.setQqdz(uri);
			log.setJgbm(loginUser.getJgbm());
			log.setDmxx((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
			// 保存数据库
			sysCzrzService.saveLog(log);

		} catch (Exception e) {
			// 记录本地异常日志
			logger.error("==前置通知异常==");
			logger.error("异常信息:{}", e.getMessage());
		}
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static Map<String,String> getBeforeControllerMethodDescription(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();
		Map<String,String> resultMap = new HashMap<String,String>();
		String description = "";
		String czmk = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemLogBeforeController.class).description();
					czmk = method.getAnnotation(
							SystemLogBeforeController.class).czmk();
					resultMap.put("description",description);
					resultMap.put("czmk",czmk);
					break;
				}
			}
		}
		return resultMap;
	}
	
	public static Map<String,String> getAfterControllerMethodDescription(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();
		Map<String,String> resultMap = new HashMap<String,String>();
		String description = "";
		String czmk = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemLogAfterController.class).description();
					czmk = method.getAnnotation(
							SystemLogAfterController.class).czmk();
					resultMap.put("description",description);
					resultMap.put("czmk",czmk);
					break;
				}
			}
		}
		return resultMap;
	}
	 /**  
     * 获取注解中对方法的描述信息 用于service层注解  
     *  
     * @param joinPoint 切点  
     * @return 方法描述  
     * @throws Exception
     */    
     public  static Map<String,String> getServiceMthodDescription(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();
        Map<String,String> resultMap = new HashMap<String,String>();
        String description = "";
        String czmk = "";
         for (Method method : methods) {
             if (method.getName().equals(methodName)) {    
                Class[] clazzs = method.getParameterTypes();
                 if (clazzs.length == arguments.length) {    
                    description = method.getAnnotation(SystemLogService.class).description();
                    czmk = method.getAnnotation(
							SystemLogService.class).czmk();
                    resultMap.put("description",description);
                    resultMap.put("czmk",czmk);
                     break;    
                }    
            }    
        }    
         return resultMap;
    } 
}


3、在方法中做应用
Controller层
/**
     * 操作日志首页
     * @param mapAdapter
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "init")
    @SystemLogAfterController(description = "操作日志首页初始化",czmk = "操作日志")
    public ModelAndView init(@RequestMap MapAdapter mapAdapter, HttpServletRequest request, HttpServletResponse response) {
        mapAdapter.getMap().put("basePath", request.getContextPath() + "/");
        return new ModelAndView("jsp/system/czrz/czrzInit",mapAdapter.getMap());
    }


Service层
@Override
    @SystemLogService(description = "保存操作日志",czmk = "操作日志")
    public void saveLog(SysLog sysLog) throws Exception {
        sysCzrzDao.insert(sysLog);
    }

    @Override
    @SystemLogService(description = "查询操作日志",czmk = "操作日志")
    public Map<String, Object> queryLogList(Map<String, Object> map) throws Exception {
        PageInfo pageInfo=sysCzrzDao.selectPage("com.winning.common.dao.impl.SysCzrzDaoImpl.selectPage",map);
        return  CommonUtils.pageInfoToBootstrapList(pageInfo);
    }


6、日志的记录效果

项目操作日志记录(方法级别)
            
    
    博客分类: SSH+i/mbatis  
  • 项目操作日志记录(方法级别)
            
    
    博客分类: SSH+i/mbatis  
  • 大小: 44.8 KB