1: Log entity class
public class SysLog { /** */ private Integer id; /** Log description*/ private String description; /** Execution method*/ private String method; /** Log type 0: Operation log; 1: Exception log*/ private Integer logType; /** ip address requested by the client*/ private String requestIp; /** Exception code*/ private String exceptionCode; /** Exception details*/ private String exceptionDetail; /** Request parameters*/ private String params; /** Operator*/ private String createBy; /** Operation time*/ private String createDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Integer getLogType() { return logType; } public void setLogType(Integer logType) { this.logType = logType; } public String getRequestIp() { return requestIp; } public void setRequestIp(String requestIp) { this.requestIp = requestIp; } public String getExceptionCode() { return exceptionCode; } public void setExceptionCode(String exceptionCode) { this.exceptionCode = exceptionCode; } public String getExceptionDetail() { return exceptionDetail; } public void setExceptionDetail(String exceptionDetail) { this.exceptionDetail = exceptionDetail; } public String getParams() { return params; } public void setParams(String params) { this.params = params; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; }}2: The jar required by maven
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.5.RELEASE</version></dependency>
The project is required to use jdk1.7
3: springServlet-mvc.xml
<!--proxy-target-class="true" Force the use of cglib proxy. If false, spring will automatically select --> <aop:aspectj-autopproxy proxy-target-class="true"/>
Adding proxy-target-class="true" is to intercept the methods in the controller.
4: Define the section, I mainly write pre-notations and exception notifications here
Below is the custom annotation
import java.lang.annotation.*;@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log {/** The type of operation to be performed, such as: add operation**/ public String operationType() default ""; /** The specific operation to be performed, such as: add user**/ public String operationName() default "";}Face-cut
import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Date;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import com.gtcity.user.model.SysLog;import com.gtcity.user.model.SysUser;import com.gtcity.user.service.SysLogService;/** * @author panliang * @version Creation time: 2017-3-31 * @desc Point-cut class* */@Aspect@Componentpublic class SystemLogAspect {//Inject Service to save the logs to the database @Resource private SysLogService systemLogService; private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class); //Controller layer tangent point//The first * represents all return value types//The second * represents all classes//The third * represents all methods of the class//The last... represents all parameters. @Pointcut("execution (* com.gtcity.web.controller..*.*(..))") public void controllerAspect() { } /** * * @author: panliang * @time: 2017-3-31 2:22:16 pm * @param joinPoint point-cut * @description: Pre-notification is used to intercept the controller layer to record the user's operations*/ @Before("controllerAspect()") public void doBefore(JoinPoint joinPoint) {/* System.out.println("============================================================================== System.out.out.info("before " + joinPoint); }*/ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //Read the user in the session SysUser user = (SysUser) session.getAttribute("user"); if(user==null){ user=new SysUser(); user.setUserName("non-registered user"); } //Requested IP String ip = request.getRemoteAddr(); 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; } } } //*====================*// System.out.println("========== Controller Pre-Notice Start=============); System.out.println("Request Method:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType); System.out.println("Method description:" + operationName); System.out.println("Requester:" + user.getUserName()); System.out.println("Request IP:" + ip); //*============ Database log=========*// SysLog log = new SysLog(); log.setDescription(operationName); log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType); log.setLogType(0); log.setRequestIp(ip); log.setExceptionCode(null); log.setExceptionDetail(null); log.setParams(null); log.setCreateBy(user.getUserName()); log.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.setRequestIp(ip); //Save the database systemLogService.insert(log); System.out.println("======== controller pre-notification end======"); } catch (Exception e) { //Record local exception log logger.error("==Pre-notification exception=="); logger.error("Exception information:{}", e.getMessage()); } } /** * * @author: panliang * @time: 2017-3-31 2:24:36 pm * @param joinPoint point-cut * @description: Exception notification is used to intercept and record exception log*/ @AfterThrowing(pointcut = "controllerAspect()", throwing="e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //Read the user in the session SysUser user = (SysUser) session.getAttribute("user"); if(user==null){ user=new SysUser(); user.setUserName("non-registered user"); } //Requested IP String ip = request.getRemoteAddr(); String params = ""; if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) { params=Arrays.toString(joinPoint.getArgs()); } 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; } } } /*==============Console output========*/ System.out.println("================Exception notification start============================================================================================================================================================================================================================================================================================================================================================================== System.out.println("Exception information:" + e.getMessage()); System.out.println("Exception method:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType); System.out.println("Method description:" + operationName); System.out.println("Requester:" + user.getUserName()); System.out.println("Request IP:" + ip); System.out.println("Request Parameters:" + params); //=============== Database Log======== SysLog log = new SysLog(); log.setDescription(operationName); log.setExceptionCode(e.getClass().getName()); log.setLogType(1); log.setExceptionDetail(e.getMessage()); log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); log.setParams(params); log.setCreateBy(user.getUserName()); log.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.setRequestIp(ip); //Save the database systemLogService.insert(log); System.out.println("========Exception notification end=========); } catch (Exception ex) { //Record local exception logger.error("==Exception notification exception=="); logger.error("Exception information:{}", ex.getMessage()); } //==============Login local exception log============ logger.error("Exception method:{}Exception code:{}Exception information:{} Parameters:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params); } }5: In the controller
/** * Find the password based on the user name to determine whether the user name and password are correct* @author panliang * @param request * @param response * @throws IOException */@RequestMapping("/skipPage.do")@Log(operationType="select operation:",operationName="user login")//Note: If this is not added, the logging of this method will not be inserted public ModelAndView skipPage(HttpServletRequest request,HttpServletResponse response) throws IOException{ModelAndView result=null;String username = request.getParameter("email");String password = request.getParameter("password");int flag = sysUserService.login(request, username, password);if(flag==1){//Login successfully result=new ModelAndView("redirect:/login/dispacher_main.do");}else if(flag==2){//The username does not exist result=new ModelAndView("redirect:/login/login.do?errorCode=1");} else{//Password is incorrect result=new ModelAndView("redirect:/login/login.do?errorCode=2");}return result;}For those who want to know about the other three notifications, please refer to this blog post: Click to open the link
In this way, when the user accesses the background, there will be records whether it is normal access or bug database.
The above AOP annotation method to implement global log management is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.