Implementation of System Log Recording Management by Spring AOP Custom Annotation

Posted by dwees on Tue, 02 Jul 2019 22:35:43 +0200

Preface

Recently, I'm a little busy. I haven't blogged for a long time. I'm a little ashamed. A few days ago, there was a requirement: to record the log of the operation of the management platform (PC side). Today, I just have time to sort out the records for you to study and discuss.

bug

Many examples on the Internet are similar, the author found a pit: for example, your cut-off point is in the business control layer (Controller), then whether it is custom log annotations or not, it will execute the log processing method. That's one of the reasons why I wrote this blog.

Code

Custom Annotation Class: LogAnnotation.java
package com.kilomob.powernetwork.managerweb.annotation;

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

/**
 * 
 * @Description
 * @author fengjk
 * @date 2017-4-25 8:28:45 p.m.
 */
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {

	/** Specific actions to be performed, such as adding users**/
	public String operationName() default "";

}
Log Interception Processing Class:
package com.kilomob.powernetwork.managerweb.annotation;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
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 com.alibaba.fastjson.JSONObject;
import com.kilomob.powernetwork.common.service.permission.SysLogService;

/**
 * 
 * @Description Logging
 * @author fengjk
 * @date 2017-5-2 3:24:37 p.m.
 */
@Aspect
@Component
public class SystemLogAspect{
	// Injection Service for saving logs to the database
	@Autowired
	SysLogService logService;
	
	private static final Logger logger = LoggerFactory
			.getLogger(SystemLogAspect.class);

	/**
	 * 
	 * @Description Post-notification, recording user's operation record in Controller
	 * @author fengjk
	 * @date 2017-4-26 11:26:59 a.m.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void afterPointCut(JoinPoint joinPoint) {
		
		try {
			
			Class[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getMethod().getParameterTypes();
			Method method = null;   
	        String methodName = joinPoint.getSignature().getName(); 
	        Class targetClass = joinPoint.getTarget().getClass();     
            method = targetClass.getMethod(methodName,parameterTypes); 
            boolean hasAnnotation = method.isAnnotationPresent(LogAnnotation.class);
            if(hasAnnotation){
            	
            	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
        				.getRequestAttributes()).getRequest();
        		String ip = getIpAddress(request);
        		// Read users in session
        		HttpSession session = request.getSession();
        		String loginName = (String) session.getAttribute("loginName");
        		Long userId = (Long) session.getAttribute("userId");
            	
            	String operationName = method.getAnnotation(LogAnnotation.class).operationName();
            	JSONObject paramObject = new JSONObject();
    			paramObject.put("account", loginName);
    			paramObject.put("userId", userId);
    			paramObject.put("ipAddress", ip);
    			paramObject.put("description", operationName);
    			paramObject.put("time", new Date());
    			paramObject.put("method", (joinPoint.getTarget().getClass().getName() + "."
    					+ joinPoint.getSignature().getName() + "()"));
    			logService.insertSysLog(paramObject);
            }
	        
		} catch (Exception e) {
			// Record local exception log
			logger.warn("Log exception information:", e);
		}
	}
	
	private String getIpAddress(HttpServletRequest request){
		
		String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	    
	}

}
if statement hasAnnotation judgment is extremely important, judging whether the interception method is a custom annotation, otherwise stepping on the pit is the way it will intercept all the annotations. SysLogService is the log insertion database interface class, where no code is pasted.
Finally, the configuration file: applicationContext.xml
<!--section,Logging -->
 	<bean id="systemLogAspect"
	class="com.kilomob.powernetwork.managerweb.annotation.SystemLogAspect"></bean>
	<aop:config>
		<aop:aspect ref="systemLogAspect">
			<aop:pointcut id="logPointCut"
				expression="execution(* com.kilomob.powernetwork.managerweb.controller..*.*(..))" />
			<aop:after pointcut-ref="logPointCut" method="afterPointCut" />
		</aop:aspect>
	</aop:config>
Note: The file method method name should be consistent with the interception class processing method
Refer to annotations and add them directly to the Controller method, such as @LogAnnotation (operation Name= "new user"), which requires recording operation logs (new add, modify, delete operations are recorded by the author).

summary

The article only provides core code, not Demo. First, there is no time to organize, and second, it is conducive to the readers themselves to explore and deepen the impact.If there are any errors in writing, please leave a message. Thank you. Welcome to join the group to discuss learning, QQ group: 583138104


Topics: Java Session Database xml