溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

封裝系統(tǒng)全局操作日志aop攔截且可打包給其他項(xiàng)目依賴

發(fā)布時(shí)間:2021-10-20 17:09:38 來源:億速云 閱讀:223 作者:柒染 欄目:大數(shù)據(jù)

封裝系統(tǒng)全局操作日志aop攔截且可打包給其他項(xiàng)目依賴,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

在開發(fā)過程中,為了更快地排錯(cuò),更好得了解接口訪問量,可以選擇用aop做全局的操作攔截,在項(xiàng)目不止一個(gè)的時(shí)候,我們可以選擇獨(dú)立出來,新項(xiàng)目可以很快的加上全局操作日志,具體代碼及數(shù)據(jù)庫表設(shè)計(jì)如下:

1.數(shù)據(jù)庫MySQL表結(jié)構(gòu)設(shè)計(jì),如下圖(可根據(jù)需要加減字段):
封裝系統(tǒng)全局操作日志aop攔截且可打包給其他項(xiàng)目依賴

2.可以根據(jù)表結(jié)構(gòu)逆向生成相關(guān)實(shí)體類及Mapper,此步驟相對(duì)簡(jiǎn)單(略)

3.增加全局日志切面類

**
 * @author songlonghui
 * @ClassName SystemLogAspect
 * @Description 日志切面記錄
 * @date 2019/7/24 16:38
 * @Version 1.0
 */
@Component
@Aspect
public class SystemLogAspect {

    private Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    private SystemLogDao systemLogDao;

    /*@Value("${LOG_POINT_URL}")
    private String logPointUrl;*/

    /** 以 controller 包下定義的所有請(qǐng)求為切入點(diǎn) */
    @Pointcut("execution(public * com.machinsight.*.*.controller..*.*(..)) && !@annotation(com.machinsight.system_log.core.annotation.NoAspectAnnotation)")
    public void webLog() {
        //logger.warn("切點(diǎn)路徑---------->" + logPointUrl);
    }

    //private SystemLogWithBLOBs systemLogWithBLOBs;

    /**
     * 在切點(diǎn)之前織入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 開始打印請(qǐng)求日志
        //logger.info("=========================================== Start ===========================================");
    }

    /**
     * 在切點(diǎn)之后織入
     * @throws Throwable
     */
    @After("webLog()")
    public void doAfter() throws Throwable {
        logger.info("=========================================== End ===========================================");
        // 每個(gè)請(qǐng)求之間空一行
        logger.info("");
    }

    /**
     * 環(huán)繞
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 開始時(shí)間
        long startTime = System.currentTimeMillis();
        SystemLogWithBLOBs systemLogWithBLOBs = new SystemLogWithBLOBs();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes){
            HttpServletRequest request = attributes.getRequest();
            logger.error("當(dāng)前線程號(hào):--doAround--" + Thread.currentThread());
            String url = request.getRequestURL().toString();
            String description = proceedingJoinPoint.getSignature().getDeclaringTypeName();
            String requestArgs = FastJsonUtils.toJSONNoFeatures(proceedingJoinPoint.getArgs()).replaceAll("\\\\","");
            String ip = UuidUtil.getIpAddr(request);
            // 打印請(qǐng)求相關(guān)參數(shù)
            logger.info("========================================== Start ==========================================");
            // 打印請(qǐng)求 url
            logger.info("請(qǐng)求URL            : {}", url);
            // 打印 Http method
            logger.info("HTTP請(qǐng)求方法 Method    : {}", request.getMethod());
            // 打印調(diào)用 controller 的全路徑以及執(zhí)行方法
            logger.info("Class--Controller 全路徑以及執(zhí)行方法 Method   : {}.{}", description);
            // 打印請(qǐng)求的 IP
            logger.info("請(qǐng)求IP             : {}", ip);
            // 打印請(qǐng)求入?yún)?
            logger.info("請(qǐng)求參數(shù)Request Args   : {}", requestArgs);
            // 記錄日志入庫
            String value = request.getHeader("user-agent");  // 用戶代理信息
            //
            systemLogWithBLOBs.setCreateTime(new Date());  // 請(qǐng)求參數(shù)
            systemLogWithBLOBs.setMethod(url);  // 接口地址
            systemLogWithBLOBs.setRequestIp(ip);  //請(qǐng)求ip
            systemLogWithBLOBs.setRequestArgs(requestArgs);  // 請(qǐng)求參數(shù)
            systemLogWithBLOBs.setUserAgent(value); // 用戶代理信息
            systemLogWithBLOBs.setDescription(description);
        }
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();

            String responseArgs = FastJsonUtils.toJSONNoFeatures(result).replaceAll("\\\\","");

            long useTime = System.currentTimeMillis() - startTime;

            // 打印出參
            logger.info("具體返回參數(shù) Response Args  : {}", responseArgs);
            // 執(zhí)行耗時(shí)
            logger.info("整體執(zhí)行耗時(shí) Time-Consuming : {} ms", useTime);
            systemLogWithBLOBs.setResponseArgs(responseArgs);
            systemLogWithBLOBs.setTimeConsuming(Integer.valueOf(String.valueOf(useTime)));
        } catch (Throwable throwable) {
            // 設(shè)置異常信息
            systemLogWithBLOBs.setIsException(1);
            // 異常信息
            systemLogWithBLOBs.setExceptionDetail(throwable.getMessage());
            // 耗時(shí)
            long exceptionTime = System.currentTimeMillis() - startTime;
            systemLogWithBLOBs.setTimeConsuming(Integer.valueOf(String.valueOf(exceptionTime)));
            // 異常返回參數(shù)
            JsonResult jsonResult = new JsonResult();
            jsonResult.setMsg(CrmConstant.OPS_FAILED_MSG);
            jsonResult.setSuccess(CrmConstant.OPS_FAILED_CODE);
            jsonResult.setData(throwable.getMessage());
            String responseArgsForException = FastJsonUtils.toJSONNoFeatures(jsonResult);
            systemLogWithBLOBs.setResponseArgs(responseArgsForException);
            // 拋出異常
            throw new Throwable(throwable.getMessage());
        } finally {
            systemLogDao.insertSelective(systemLogWithBLOBs);
        }
        return result;
    }

4.可根據(jù)公司項(xiàng)目的整體包結(jié)構(gòu)配置切點(diǎn),還可以增加不需要攔截的配置,為了更靈活細(xì)化,這里增加了相應(yīng)注解類,如下:

/**
 * 切面排除注解類
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NoAspectAnnotation {

}

5.只要在不需要的攔截的controller方法加上注解@NoAspectAnnotation即可,切點(diǎn)會(huì)自動(dòng)排除:

/**
 * @author songlonghui
 * @ClassName CommonController
 * @Description TODO
 * @date 2019/8/23 16:09
 * @Version 1.0
 */
@Controller
@RequestMapping("common")
public class CommonController {

    @ResponseBody
    @RequestMapping("/test")
    @NoAspectAnnotation
    public String testLog(@RequestBody String inputJson) throws Exception{
        String msg = "操作成功";
        return msg;
    }

}

6.只要在別的項(xiàng)目中增加該項(xiàng)目依賴即可:

<!-- 全局日志切面 -->
<dependency>
   <groupId>com.machinsight</groupId>
   <artifactId>system_log</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <exclusions>
      <exclusion>
         <artifactId>*</artifactId>
         <groupId>*</groupId>
      </exclusion>
   </exclusions>
</dependency>

有需要整體項(xiàng)目源碼的朋友可以聯(lián)系我,現(xiàn)在還沒有想好源碼放在什么地方供別人下載??!
郵箱地址:lance911215@outlook.com

關(guān)于封裝系統(tǒng)全局操作日志aop攔截且可打包給其他項(xiàng)目依賴問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

aop
AI