Method Description section:
- @Aspect - effect of the current class is identified as a read section for the container
- @Pointcut - (entry point): is the connection point with a notice in the program is mainly writing pointcut expressions
- @Before - identifies a pre-enhancement methods, functional equivalent BeforeAdvice
- Enhance the implementation of the post, the equivalent of AfterReturningAdvice, when the method exits - @AfterReturning
- @AfterThrowing - enhanced exception is thrown, the equivalent of ThrowsAdvice
- @After - final enhancement, whether it is throwing an exception or normal exit will be executed
- @Around - Surround enhancements, equivalent to MethodInterceptor
Codes (refer to ' Zoe ')
In the configuration file pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
@Aspect @Component public class LogAspect { Private static Final Logger LoggerFactory.getLogger = log (LogAspect. Class ); // disposed weaving point @Pointcut ( "Annotation @ (com.ruoyi.common.annotation.Log)" ) public void logPointCut () { } / ** execution request has been handled post * * * @param Joinpoint tangent point * / @AfterReturning (the pointcut = "logPointCut ()", returning = "JsonResult" ) public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) { handleLog(joinPoint, null, jsonResult); } /** * 拦截异常操作 * * @param joinPoint 切点 * @param e 异常 */ @AfterThrowing(value = "logPointCut()", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Exception e) { handleLog(joinPoint, e, null); } protected void handleLog(final JoinPoint joinPoint, finalE Exception, Object JsonResult) { the try { // get notes the Log controllerLog = getAnnotationLog (Joinpoint); IF (controllerLog == null ) { return ; } // get the current user SYSUSER the currentUser = ShiroUtils.getSysUser (); // * * log database ======== ========= // SysOperLog operLog = new new SysOperLog (); operLog.setStatus (BusinessStatus.SUCCESS.ordinal ()); // requested address String ip = ShiroUtils.getIp(); operLog.setOperIp(ip); // 返回参数 operLog.setJsonResult(JSON.marshal(jsonResult)); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); if (currentUser != null) { operLog.setOperName(currentUser.getLoginName()); if (StringUtils.isNotNull(currentUser.getDept()) && StringUtils.isNotEmpty(currentUser.getDept().getDeptName())) { operLog.setDeptName(currentUser.getDept().getDeptName()); } } if (e != null ) { operLog.setStatus (BusinessStatus.FAIL.ordinal ()); operLog.setErrorMsg (StringUtils.substring (e.getMessage (), 0, 2000 )); } // set the method name String className = joinPoint.getTarget () .getClass () getName ();. String methodName = joinPoint.getSignature () getName ();. operLog.setMethod (className + + methodName + "()". "" ); // set request method operLog.setRequestMethod (ServletUtils .getRequest () getMethod ());. // process parameters set annotations getControllerMethodDescription (controllerLog, operLog); // save the database AsyncManager.me () Execute (AsyncFactory.recordOper (operLog));. } the catch (Exception exp) { // record local anomaly log log.error ( "== pre-notification exception == " ); log.error ( " exception information: {} " , exp.getMessage ()); exp.printStackTrace (); } } / ** * Get the annotation information is described a method for annotation layer Controller * * @param log log * @param operLog operation log * @throwsException * / public void getControllerMethodDescription (the Log log, SysOperLog operLog) throws Exception { // set action action operLog.setBusinessType (log.businessType () ORDINAL ().); // set the title operLog.setTitle (log.title ()) ; // set the operator category operLog.setOperatorType (log.operatorType () ORDINAL ().); // you have saved request, parameters and values iF (log.isSaveRequestData ()) { // access to information parameters passed to the database. setRequestValue (operLog); } } / ** * Acquisition parameters of the request, into the log * * @param operLog operation log * @throws Exception exception * / Private void setRequestValue (SysOperLog operLog) throws Exception { the Map <String, String []> = Map ServletUtils.getRequest (). getParameterMap (); String the params = JSON.marshal (Map); operLog.setOperParam (StringUtils.substring (the params, 0, 2000 )); } / ** * presence or absence of annotations, if it exists acquired * / Private the Log getAnnotationLog (the JoinPoint Joinpoint) throws Exception { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(Log.class); } return null; } }
package com.ruoyi.framework.manager.factory; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.utils.AddressUtils; import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.framework.shiro.session.OnlineSession; import com.ruoyi.framework.util.LogUtils; import com.ruoyi.framework.util.ShiroUtils; import com.ruoyi.system.domain.SysLogininfor; import com.ruoyi.system.domain.SysOperLog; import com.ruoyi.system.domain.SysUserOnline; import com.ruoyi.system.service.ISysOperLogService; import com.ruoyi.system.service.ISysUserOnlineService; import com.ruoyi.system.service.impl.SysLogininforServiceImpl; import eu.bitwalker.useragentutils.UserAgent; /** * 异步工厂(产生任务用) * * @author liuhulu * */ public class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** Synchronization session to the database * * * @param session online user session * @return Task Task * / public static the TimerTask syncSessionToDb ( Final OnlineSession session) { return new new the TimerTask () { @Override public void RUN () { SysUserOnline Online = new new SysUserOnline ( ); online.setSessionId (String.valueOf (session.getId ())); online.setDeptName (session.getDeptName ()); online.setLoginName (session.getLoginName ()); online.setStartTimestamp(session.getStartTimestamp()); online.setLastAccessTime(session.getLastAccessTime()); online.setExpireTime(session.getTimeout()); online.setIpaddr(session.getHost()); online.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost())); online.setBrowser(session.getBrowser()); online.setOs(session.getOs()); online.setStatus(session.getStatus()); SpringUtils.getBean(ISysUserOnlineService.class).saveOnline(online); } }; } / ** }; * 操作日志记录 * * @Param operLog operation log information * @return task Task * / public static TimerTask recordOper ( Final SysOperLog operLog) { return new new TimerTask () { @Override public void RUN () { // remotely query sites operLog.setOperLocation (AddressUtils. getRealAddressByIP (operLog.getOperIp ())); SpringUtils.getBean (ISysOperLogService. class ) .insertOperlog (operLog); } } / ** * record login information * * @param username 用户名 * @param status 状态 * @param message 消息 * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = ShiroUtils.getIp(); return new TimerTask() { @Override public void run() { String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); s.append(address); s.append(LogUtils.getBlock(username)); s.append(LogUtils.getBlock(status)); s.append(LogUtils.getBlock(message)); // 打印信息到日志 sys_user_logger.info (s.toString (), args); // get client operating system String os = userAgent.getOperatingSystem () getName ();. // get the client browser String Browser = userAgent.getBrowser () getName. (); // encapsulate the object SysLogininfor logininfor = new new SysLogininfor (); logininfor.setLoginName (username); logininfor.setIpaddr (IP); logininfor.setLoginLocation (address); logininfor.setBrowser (Browser); logininfor.setOs (OS); logininfor.setMsg (Message); // log status if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) { logininfor.setStatus(Constants.SUCCESS); } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus(Constants.FAIL); } // 插入数据 SpringUtils.getBean(SysLogininforServiceImpl.class).insertLogininfor(logininfor); } }; } }
Entry point (notes)
package com.ruoyi.common.annotation; 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; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.enums.OperatorType; /** * 自定义操作日志记录注解 * * @author ruoyi */ @Target({ ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface the Log { / ** * Module * / public String title () default "" ; / ** * function * / public BusinessType BusinessType () default BusinessType.OTHER; / ** * operator Type * / public OperatorType operatorType () default OperatorType.MANAGE; / ** * whether to save the requested parameter * / public Boolean isSaveRequestData () default to true ; }
Call the method, red block