Spring MVC records operation log to database

Database fields

TABLE statement

CREATE TABLE log_table (
Log [id int (11) not null auto [incremental comment 'primary key',
Log [IPAddress varchar (64) default null comment 'requested IP address',
Log [createtime varchar (64) default null comment 'time',
Log [modulename varchar (128) default null comment 'module name',
Log desc varchar (128) default null comment 'function',
Log U type varchar (32) default null comment 'operation type',
Log [methodname varchar (128) default null comment 'requested method name',
Log params varchar (1000) default null comment 'requested parameter',
Log ﹣ paramter varchar (2000) default null comment 'requested parameter',
PRIMARY KEY (log_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT = 'operation log table';

Configure application-aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
	
	<!-- Configuring package scanners, scanning@Service Class of primary key[Only packages in the background are scanned here] -->
	<context:component-scan base-package="com.kindergarten.log"></context:component-scan>  

	<!-- Define operation log facet -->
	<bean id="logAspect" class="com.kindergarten.log.LogAopAspect"></bean>
	<!-- notice Spring Use cglib Instead of jdk To generate a proxy method  AOP Can be intercepted Controller -->
	<aop:aspectj-autoproxy proxy-target-class="true">
		<aop:include name="logAspect"/>
	</aop:aspectj-autoproxy>

Entity class

package com.kindergarten.log;

public class Logentity {
	/**
	 * Primary key
	 **/
    private String logId = "";
	/**
	 * Requested IP address
	 **/
    private String logIpAddress = "";
	/**
	 * time
	 **/
    private String logCreatetime = "";
	/**
	 * Module name
	 **/
    private String logModulename = "";
	/**
	 * function
	 **/
    private String logDesc = "";
    /**
	 * Operation type 
	 **/
    private String logType = "";
	/**
	 * Requested method name
	 **/
    private String logMethodname = "";
	/**
	 * Requested parameters
	 **/
    private String logParams = "";
   	/**
   	 * Requested parameters
   	 **/
    private String logParamter = "";
    
    
    
    
	public String getLogId() {
		return logId;
	}
	public void setLogId(String logId) {
		this.logId = logId;
	}
	public String getLogIpAddress() {
		return logIpAddress;
	}
	public void setLogIpAddress(String logIpAddress) {
		this.logIpAddress = logIpAddress;
	}
	public String getLogCreatetime() {
		return logCreatetime;
	}
	public void setLogCreatetime(String logCreatetime) {
		this.logCreatetime = logCreatetime;
	}
	public String getLogModulename() {
		return logModulename;
	}
	public void setLogModulename(String logModulename) {
		this.logModulename = logModulename;
	}
	public String getLogDesc() {
		return logDesc;
	}
	public void setLogDesc(String logDesc) {
		this.logDesc = logDesc;
	}
	public String getLogType() {
		return logType;
	}
	public void setLogType(String logType) {
		this.logType = logType;
	}
	public String getLogMethodname() {
		return logMethodname;
	}
	public void setLogMethodname(String logMethodname) {
		this.logMethodname = logMethodname;
	}
	public String getLogParams() {
		return logParams;
	}
	public void setLogParams(String logParams) {
		this.logParams = logParams;
	}
	public String getLogParamter() {
		return logParamter;
	}
	public void setLogParamter(String logParamter) {
		this.logParamter = logParamter;
	}
	
    
}

Service interface

package com.kindergarten.log;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kindergarten.mapper.LogMapper;

@Service
public class LogServiceImpl implements LogService{
	@Autowired
	private LogMapper logMapper;
	/**
	 *add log 
	*/
	@Override
	public void insertlog(Logentity logentity){
		logMapper.insertlog(logentity);
	}
}

Service

package com.kindergarten.log;

public interface LogService {
	/**
	 *add log 
	*/
	public void insertlog(Logentity logentity);
}

Log section

package com.kindergarten.log;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.kindergarten.util.DateUtil;
import com.kindergarten.util.IpAddress;

import java.util.HashMap;

@Aspect
@Component
public class LogAopAspect {
	private static final Logger LOGGER = LoggerFactory.getLogger(LogAopAspect.class);
	@Autowired
	private LogService logService;
	
	/**
	 * Controller Layer tangent point 
	 */
	@Pointcut("@annotation(com.kindergarten.log.LogAopPointcut)")
	public void aopPoint() {
		
	}
	
	
	/**
	 * Section configuration notification 
	 */
    @AfterReturning("aopPoint()")
    public void saveSysLog(JoinPoint joinPoint) {
        //Save log
        Logentity log = new Logentity();
        
        //The method of obtaining the weaving point by reflection mechanism from the section weaving point
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //How to get the pointcut
        Method method = signature.getMethod();

        //Acquisition operation
        LogAopPointcut logAopPointcut = method.getAnnotation(LogAopPointcut.class);
        //--------------------
        if (logAopPointcut != null) {
        	//Module name
            log.setLogModulename(logAopPointcut.logModulename());
            //function
            log.setLogDesc(logAopPointcut.logDesc());
            //Operation type
            String index = logAopPointcut.logType().getIndex();
            String name = logAopPointcut.logType().getLogname();
            log.setLogType(name);
        }
        
        //time
        log.setLogCreatetime(DateUtil.getDate_YMDHMS_S());
        //--------------------
        //Get the requested method name
        String methodName = method.getName();
        log.setLogMethodname(methodName);
        //--------------------
        //Requested parameters
        Object[] args = joinPoint.getArgs();
        //Convert the array of parameters to json
        String params = JSON.toJSONString(args);
        log.setLogParams(params);
        //--------------------
        //--------------------
        //Create parameter name instance
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] paramterNames = discoverer.getParameterNames(method);
        //Parameter data passed to method
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        for (int i = 0; i < paramterNames.length; i++) {
			Object o = args[i];
			if(o instanceof String || o instanceof String[]) {
				paramsMap.put(paramterNames[i], o);
			}else {
				continue;
			}
		}
        String paramter = JSON.toJSONString(paramsMap);
        log.setLogParamter(paramter);
        //--------------------
        //Get user ip address
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        log.setLogIpAddress(IpAddress.getIpAddress(request));
        //--------------------
//        //Get user name
//        sysLog.setUsername(ShiroUtils.getUserEntity().getUsername());
  

        //Call service to save the log entity class to the database
        logService.insertlog(log);
    }

}

Define operation log category

package com.kindergarten.log;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 1.CONSTRUCTOR:Used to describe the constructor
 * 2.FIELD:Used to describe a domain
 * 3.LOCAL_VARIABLE:Used to describe local variables
 * 4.METHOD:Used to describe the method
 * 5.PACKAGE:Used to describe a package
 * 6.PARAMETER:Used to describe parameters
 * 7.TYPE:Used to describe a class, interface (including annotation types), or enum declaration
 * */
@Target({ElementType.METHOD})//Method
/**
 * 1,RetentionPolicy.SOURCE: Annotations are only kept in source files. When Java files are compiled into class files, annotations are discarded;
 * 2,RetentionPolicy.CLASS: The annotation is reserved to the class file, but it is abandoned when the jvm loads the class file, which is the default life cycle;
 * 3,RetentionPolicy.RUNTIME: Annotations are not only saved to the class file, but still exist after the class file is loaded by the jvm
 * */
@Retention(RetentionPolicy.RUNTIME)
/**
 * Documented Annotation indicates that this annotation is recorded by javadoc, and there are similar recording tools by default.
 *  If a type declaration is annotated and documented, its annotations become part of the public API
 * */
@Documented
public @interface LogAopPointcut 
{
	public abstract String logModulename();
	public abstract String logDesc();
	public abstract log_Type logType();
	
	public static enum log_Type
	{
		SELECT,ADD,UPDATE,DELETE,EXPORT,IMPORT;
		
		private String logname;
		private String index;
		
		public String getLogname() {
			return this.name();
		}
		public String getIndex() {
			return String.valueOf(this.ordinal()+1);
		}
				
	}
}

Use the custom @ LogAopPointcut on the method you want to record

Example:

Example: @ LogAopPointcut(logModulename = student module, logDesc = condition query, logtype = log Ou type. Select)

@LogAopPointcut(logModulename = student module, logDesc = condition deletion, logType = log_Type.SELECT)

/** Conditional query */
	@RequestMapping(value = "/findStudent", produces = "application/json;charset=UTF-8")
	@ResponseBody
	@LogAopPointcut(logModulename = "Student module",logDesc = "Conditional query",logType = log_Type.SELECT)
	public String findStudent(String starttime, String endtime, String id, String name, String age) {
		List<StudentEntity> list = studentService.findStudent(starttime, endtime, id, name, age);
		String json = JSONArray.toJSONStringWithDateFormat(list, "yyyy-MM-dd HH:mm:ss");
		return json;
	}

Database records operation information

Published 2 original articles, praised 0 and visited 11
Private letter follow

Tags: Java JSON Spring Database

Posted on Wed, 19 Feb 2020 10:20:46 -0500 by nemethpeter