Implement the global log management method by using the aop annotation method and the aop Management Method

Source: Internet
Author: User

Implement the global log management method by using the aop annotation method and the aop Management Method

1: log entity class

Public class SysLog {/***/private Integer id;/** log description */private String description;/** method of execution */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 parameter */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. predictiondetail = 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: 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 cglib proxy to be used. If it is false, spring automatically selects --> <aop: aspectj-autoproxy proxy-target-class = "true"/>

Add proxy-target-class = "true" to intercept the methods in the controller.

4: definition section. Here I mainly write pre-notifications and exception notifications.

Start the custom annotation below

Import java. lang. annotation. *; @ Target ({ElementType. PARAMETER, ElementType. METHOD}) @ Retention (RetentionPolicy. RUNTIME) @ brief ented public @ interface Log {/** operation type to be executed, such as: add operation **/public String operationType () default ""; /** specific operations to be performed, such as: adding a user **/public String operationName () default "";}

Face Cutting

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; impo Rt 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. spr Ingframework. 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: * @ desc cut point class **/@ Aspect @ Componentpublic class SystemLogAspect {// The injection Service is used to save logs to the Database @ Resource private SysLogService systemLogService; private static final Logger logger = Logg ErFactory. getLogger (SystemLogAspect. class ); // Controller layer cut point // The first * represents all return value types // The second * represents all classes // The third * represents all classes // The last .. all parameters. @ Pointcut ("execution (* com. gtcity. web. controller .. *. *(..)) ") public void controllerAspect () {}/ ***** @ author: panliang * @ time: 2:22:16 * @ param joinPoint cut point * @ describtion: pre-notification is used to intercept the Controller layer to record user operations */@ Before ("controllerAspect ()") public void doBefore (JoinPoint joinPoint) {/* System. out. println ("=========== execute controller pre-notification ======================"); if (logger. isInfoEnabled () {logger.info ("Before" + joinPoint);} */HttpServletRequest request = (ServletRequestAttributes) RequestContextHolder. getRequestAttributes ()). getRequest (); HttpSession session = request. getSession (); // read the user SysUser user = (SysUser) session in the session. getAttribute ("user"); if (user = null) {user = new SysUser (); user. setUserName ("non-registered user");} // request IP String ip = request. getRemoteAddr (); try {String targetName = joindium Oint. 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 ("===== controller pre-notification start ===="); System. out. println ("Request Method:" + (joinPoint. getTarget (). getClass (). getName () + ". "+ joinPoint. getSignature (). getName () + "()") + ". "+ operat IonType); 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); l Og. 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 systemLogService database. insert (log); System. out. println ("===== controller pre-notification end ====");} catch (Exception e) {// record the local Exception log logger. error ("= pre-notification exception ="); logger. error ("exception information: {}", e. g EtMessage () ;}}/***** @ author: panliang * @ time: 2:24:36 * @ param joinPoint cut point * @ describtion: exception notification is used to intercept abnormal logs */@ 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 SysUser user = (SysUser) session in the session. getAttribute ("user"); if (user = null) {user = new SysUser (); user. setUserName ("non-registered user");} // request 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 Code:" + e. getClass (). getName (); 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 parameter:" + 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 systemLogService database. insert (log); System. out. println ("===== Exception notification end ====");} catch (Exception ex) {// record the local Exception log logger. error ("= Exception notification exception ="); logger. error ("exception message: {}", ex. getMessage () ;}//========== record the local exception log ========== logger. error ("exception method: {} Exception Code: {} exception information: {} parameter: {}", joinPoint. getTarget (). getClass (). getName () + joinPoint. getSignature (). getName (), e. getClass (). getName (), e. getMessage (), params );}}

5: In the controller

/*** Determine whether the user name and password are correct based on the user name * @ author panliang * @ param request * @ param response * @ throws IOException */@ RequestMapping ("/skipPage. do ") @ Log (operationType =" select Operation: ", operationName =" User Logon ") // Note: If this parameter is not added, the log records of this method are not inserted into 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) {// logon success result = new ModelAndView ("redirect:/login/dispacher_main.do ");} else if (flag = 2) {// the user name does not exist result = new ModelAndView ("redirect:/login. do? ErrorCode = 1 ");} else {// incorrect password result = new ModelAndView (" redirect:/login. do? ErrorCode = 2 ");} return result ;}

For details about the other three types of notifications, refer to this blog:Click Open Link

In this way, when users access the background, both normal access and bug database records are recorded.

The above aop annotation method implements the global log management method, which is a small part of the Content shared to everyone. I hope to give you a reference and support for the help house.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.