自定义注解——日志

前提:

需要有一个日志表,然后完成日志表的CRUD

然后写自定义注解类
@Target(
{ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{

	/** 要执行的操作类型比如:add操作 **/
	public String operationType() default "";

	/** 要执行的具体操作比如:添加用户 **/
	public String operationName() default "";
}

其实只需要一个参数就够了。如果有需要可以吧第一个参数修改为操作等级之类的。第二个参数是操作描述。

然后写个拦截器

搞个拦截器 拦截所有通过控制层的请求。

/**
 * @author
 * @E-mail: email
 * @version 创建时间:
 * @desc 切点类
 */

@Aspect
@Component
public class LogInterceptor extends BaseController
{
	// 注入Service用于把日志保存数据库
	@Resource // 这里我用resource注解,一般用的是@Autowired
	private IUsersService usersService;

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

	// Controller层切点
	@Pointcut("execution (* com.xxxxx.xxxxxx.back.controller.*Controller.*(..))")
	public void controllerAspect()
	{
	}

	/*@Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) 
	{
        //System.out.println("==========执行controller前置通知===============");
        if(logger.isInfoEnabled())
        {
            logger.info("before " + joinPoint);
        }
    }*/
	/**
	 * 后置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint 切点
	 */
	@After("controllerAspect()")
	public void after(JoinPoint joinPoint)
	{
		// 读取session中的用户
		// User user = (User) session.getAttribute("user");
		// 请求的IP
		// String ip = request.getRemoteAddr();
		HttpServletRequest request = null ; 
		try
		{
			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 operationType = null;
			//String operationName = null;
			for (Method method : methods)
			{
				if (method.getName().equals(methodName))
				{
					Class[] clazzs = method.getParameterTypes();
					if (clazzs.length == arguments.length)
					{
						if (method.getAnnotation(Log.class)!=null)
						{
							operationType = method.getAnnotation(Log.class).operationType();
						}
						
						//operationName = method.getAnnotation(Log.class).operationName();
						break;
					}
				}
			}
			/*==确定request的值===*/
			for (int i = 0; i < arguments.length; i++)
			{
				Object obj = arguments[i];
				if(obj instanceof HttpServletRequest)
				{
					request = (HttpServletRequest) obj ; 
					break;  
				}
			}
			// *========控制台输出=========*//
			/*System.out.println("=====controller后置通知开始=====");
			System.out.println("请求方法:"
					+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
					+ "." + operationType);
			System.out.println("方法描述:" + operationName);*/
			/*System.out.println("请求人:" + user.getName());
			System.out.println("请求IP:" + ip);*/
			// *========数据库日志=========*//
			AAdminsLog log = new AAdminsLog();
			log.setDescription(operationType);
			log.setContent(operationType);
			log.setMethod(joinPoint.getTarget().getClass().getName());
			log.setLogType(AdminsLogEnum.LOGTYPE_COM.getStatus());
			//log.setCreateBy(user.getName());
			
			if(request != null)
			{
				String params = request.getQueryString();
				
				if (params!=null&&params.length()>=250)
				{
					params = params.substring(0, 250);
				}
				log.setParams(params);
				log.setIp(this.getIpAddress(request));
				
				HttpSession session = request.getSession() ; 
				AAdmins adminsJSON = (AAdmins) session.getAttribute("admins");
				if (adminsJSON!=null)
				{
					log.setAdminsId(adminsJSON.getId());
					log.setName(adminsJSON.getName());
				}
				
			}
			
			log.setCreateTime(new Date());
			log.setUpdateTime(new Date());
			// 保存数据库
			if (operationType!=null)
			{
				this.usersService.saveOneAdminsLogService(log);
			}
			
			//System.out.println("=====controller后置通知结束=====");
		} catch (Exception e)
		{
			e.printStackTrace();
			// 记录本地异常日志
			logger.error("==后置通知异常==");
			logger.error("异常信息:{}", e.getMessage());
		}
	}

	/**
	 * 异常通知 用于拦截记录异常日志
	 * 
	 * @param joinPoint
	 * @param e
	 */
	@AfterThrowing(pointcut = "controllerAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e)
	{
		/*
		 * HttpServletRequest request = ((ServletRequestAttributes)
		 * RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession
		 * session = request.getSession(); //读取session中的用户 User user = (User)
		 * session.getAttribute(WebConstants.CURRENT_USER); //获取请求ip String ip =
		 * request.getRemoteAddr();
		 */
		// 获取用户请求方法的参数并序列化为JSON格式字符串
		HttpServletRequest request = null ; 
		try
		{
			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 operationType = "";
			String operationName = "";
			for (Method method : methods)
			{
				if (method.getName().equals(methodName))
				{
					Class[] clazzs = method.getParameterTypes();
					if (clazzs.length == arguments.length)
					{
						operationType = method.getAnnotation(Log.class).operationType();
						operationName = method.getAnnotation(Log.class).operationName();
						break;
					}
				}
			}
			
			/*==确定request的值===*/
			for (int i = 0; i < arguments.length; i++)
			{
				Object obj = arguments[i];
				if(obj instanceof HttpServletRequest)
				{
					request = (HttpServletRequest) obj ; 
					break;  
				}
			}
			/* ========控制台输出========= */
			/*System.out.println("=====异常通知开始=====");
			System.out.println("异常代码:" + e.getClass().getName());
			System.out.println("异常信息:" + e.getMessage());
			System.out.println("异常方法:"
					+ (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
					+ "." + operationType);
			System.out.println("方法描述:" + operationName);*/
			//System.out.println("请求人:" + user.getName());
			//System.out.println("请求IP:" + ip);
			//System.out.println("请求参数:" + params);
			// *========数据库日志=========*//
			AAdminsLog log = new AAdminsLog();
			log.setDescription(operationType);
			log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")
					+ "." + operationType);
			log.setLogType(AdminsLogEnum.LOGTYPE_SER.getStatus());
			log.setExceptioncode(null);
			log.setExceptionDetail(null);
			log.setExceptioncode(e.getClass().getName());
			log.setExceptionDetail(e.getMessage());
			if(request != null)
			{
				log.setParams(request.getQueryString());
				log.setIp(this.getIpAddress(request));
				
				HttpSession session = request.getSession() ; 
				JSONObject adminsJSON = (JSONObject) session.getAttribute("adminsSess");
				log.setAdminsId(adminsJSON.getIntValue("id"));
			}
			
			log.setCreateTime(new Date());
			log.setUpdateTime(new Date());
			// 保存数据库
			this.usersService.saveOneAdminsLogService(log);
			/*System.out.println("=====异常通知结束=====");*/
		} catch (Exception ex)
		{
			// 记录本地异常日志
			logger.error("==异常通知异常==");
			logger.error("异常信息:{}", ex.getMessage());
		}
		/* ==========记录本地异常日志========== */
		logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}",
				joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(),e.getMessage());
		
	}
}
最后在控制层的方法上 添加上我们常见的注解就可以了

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

散装程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值