自定义日志注解 + AOP实现记录操作日志


需求:系统中经常需要记录员工的操作日志和用户的活动日志,简单的做法在每个需要的方法中进行日志保存操作,

但这样对业务代码入侵性太大,下面就结合AOP和自定义日志注解实现更方便的日志记录

首先看下一个简单的操作日志表

action_log

  • id
  • subject(日志主题)
  • content(日志内容)
  • create_by
  • create_time

日志主题可以用下面的枚举类来实现

package cn.bounter.common.model;

/**
 * 应用日志主题枚举类
 * @author simon
 *
 */
public enum AppLogSubjectEnum {

   /** 客户 */
   CUSTOMER(1,"客户"),
   /** 商品 */
   COMMODITY(2,"商品"),
   /** 订单 */
   ORDER(3,"订单");

   private Integer value;

   private String name;

   private AppLogSubjectEnum(int value, String name) {
      this.value = value;
      this.name = name;
   }

   public Integer getValue() {
      return value;
   }

   public String getName() {
      return name;
   }

   /**
    * 自定义方法
    * 根据枚举值获取枚举字符串内容
    * @param value
    * @return
    */
   public static String stringOf(int value) {
      for(AppLogSubjectEnum oneEnum : AppLogSubjectEnum.values()) {
         if(oneEnum.value == value) {
            return oneEnum.getName();
         }
      }
      return null;
   }

}

然后让我们看下自定义注解

package cn.bounter.common.model;

import java.lang.annotation.*;

/**
 * 应用日志注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AppLog {

    /**
     * 日志主题
     * @return
     */
    AppLogSubjectEnum subject();

    /**
     * 日志内容
     * @return
     */
    String content() default "";
}

接下来就是重头戏基于自定义注解的切面了

package cn.bounter.common.model;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 应用日志切面
 */
@Aspect
@Component
public class AppLogAspect {

    @Autowired
    private ActionLogService actionLogService;

    @Pointcut("@annotation(cn.bounter.common.model.AppLog)")
    public void appLogPointCut() {
    }

    @AfterReturning("appLogPointCut()")
    public void addActionLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        //获取注解
        AppLog appLog = method.getAnnotation(AppLog.class);
        if (appLog == null) {
            return;
        }

        //保存数据库
        actionLogService.save(
                new ActionLog()
                .setSubject(appLog.subject().getValue())
                .setContent(appLog.content())
                .setCreateBy(ShiroUtils.getUser())      //获取当前登录的用户
                .setCreateTime(LocalDateTime.now())
        );
    }

}

到这里就差不多,最后让我们看下怎么使用自定义日志注解

/**
 * 新增订单
 * @param order
 * @return
 */
@AppLog(subject = AppLogSubjectEnum.ORDER, content = "新增")
public void save(Order order) {
    orderService.save(order);
}

看完了之后是不是觉得挺简单哉!那就赶快自己动手试一试吧!

原文地址:https://www.cnblogs.com/gdufs/p/10888536.html

时间: 2024-08-05 16:54:08

自定义日志注解 + AOP实现记录操作日志的相关文章

Spring boot学习(六)Spring boot实现AOP记录操作日志

前言 在实际的项目中,特别是管理系统中,对于那些重要的操作我们通常都会记录操作日志.比如对数据库的CRUD操作,我们都会对每一次重要的操作进行记录,通常的做法是向数据库指定的日志表中插入一条记录.这里就产生了一个问题,难道要我们每次在 CRUD的时候都手动的插入日志记录吗?这肯定是不合适的,这样的操作无疑是加大了开发量,而且不易维护,所以实际项目中总是利用AOP(Aspect Oriented Programming)即面向切面编程这一技术来记录系统中的操作日志. 日志分类 这里我把日志按照面向

ThreadLocal 在记录操作日志中的应用

ThreadLocal,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,其实意思差不多.可能很多朋友都知道ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量 在HandlerInterceptor的preHandle 中可以截取crud等操作的一些url public class PlatformLogInterceptor implements HandlerInterceptor { private Logger log = LoggerF

Tomcat会话超时时怎样记录操作日志,满足安全审计要求

众所周知.在实际的Web应用程序中,会话管理一般都採用Web容器会话管理功能. 使用Tomcat做Webserver也是如此,并且从安全的角度考虑,尽量避免去更改和干预Web容器的会话管理功能. Tomcat会话管理功能肯定比我们自己做出来要全面和可靠,况且Tomcat是主流开源社区维护的.有专门的团队来开发和维护.一旦爆出安全漏洞,也能非常快被修复. 在实际开发中,为了满足安全审计的要求.Web应用程序一旦有会话注销.就应该记录操作日志.注销一般分为操作者主动注销.应用程序检測到异常攻击主动注

MVC 记录操作日志与过滤特殊字符

最近进行的MVC系统需要用到记录操作日志和过滤特殊字符的功能,如果每个action中都调用记录日志的方法就太麻烦了,所以根据需要结合mvc的过滤机制 写了个特殊字符验证与记录操作日志的公用类: 1 public class CustomFilterAttribute : ActionFilterAttribute 2 { 3 public CustomFilterAttribute() 4 { 5 IsLog = false; 6 FilterSpecialChar = true; 7 } 8

Tomcat会话超时时如何记录操作日志,满足安全审计要求

众所周知,在实际的Web应用程序中,会话管理一般都采用Web容器会话管理功能. 使用Tomcat做Web服务器也是如此,而且从安全的角度考虑,尽量避免去更改和干预Web容器的会话管理功能. Tomcat会话管理功能肯定比我们自己做出来要全面和可靠,况且Tomcat是主流开源社区维护的,有专门的团队来开发和维护,一旦爆出安全漏洞,也能很快被修复. 在实际开发中,为了满足安全审计的要求,Web应用程序一旦有会话注销,就应该记录操作日志,注销一般分为操作者主动注销.应用程序检测到异常攻击主动注销会话.

Spring aop 记录操作日志 Aspect

前几天做系统日志记录的功能,一个操作调一次记录方法,每次还得去收集参数等等,太尼玛烦了.在程序员的世界里,当你的一个功能重复出现多次,就应该想想肯定有更简单的实现方法.于是果断搜索各种资料,终于搞定了,现在上代码 环境: SpringMvc + myBatis jar包 :      (aspect.jar也行,我原来项目中有,便没有替换了) 1.自定义注解类   ArchivesLog.java(获取Controller描述用的) package com.noahwm.uomp.archive

spring-boot aop 增删改操作日志 实现

1.注解接口:import com.github.wxiaoqi.security.common.constant.Constants; import java.lang.annotation.*; /** * 日志注解 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SysLogOpt { String value(); String module() de

asp.net MVC自定义错误页,并记录错误日志

只需要在Global.asax文件中添加以下代码,则可以在出错后友好的展示错误页,也不需要在很多地方写记录错误日志的代码 protected void Application_Error(object sender, EventArgs e) { if (HttpContext.Current.IsCustomErrorEnabled) { return; } var exception = Server.GetLastError(); var httpException = new HttpE

Nginx 指定不产生日志类型(不记录图片日志)

在主配置文件中已经定义了配置文件的格式 [[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf  # nginx 中的配置修改 日志命名格式 log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]' '$host "$request_uri" $status' '"$http_referer" "