【Java工具】计时器aop工具日志打印

效果

 

使用方法

	@Override
	@TimerLog        //计时
	public int synSaledetail() throws Exception {
		return this.synSaledetail();
	}

 

代码

package com.base.common.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Console;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @program:
 *
 * @description: 计时器aop
 *
 * @author: Mr.Guan
 *
 * @Mail: GuanWeiMail@163.com
 *
 * @create: 2018
 **/
@Component
@Scope
@Aspect
public class TimerLogAspect {

    /**
     * Service层切点  增加时间日志
     * TODO 该路径应写成TimerLogHutool注解的路径
     */
    @Pointcut("@annotation(com.rhm.base.common.aop.TimerLog)")
    public void ServiceAspect() {

    }

    @Around("ServiceAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) {
        Object obj = null;


        //获取方法名称
        String methodName = joinPoint.getSignature().getName();
        //获取类名
        String name = joinPoint.getTarget().getClass().getName();
        //开启计时
        TimeInterval timer = DateUtil.timer();
        Console.log("【计时器@TimerLog】{}.{} - 开启计时,方法执行中...", name, methodName);
        try {
            //执行方法
            obj = joinPoint.proceed();
            Console.log("【计时器@TimerLog】{}.{} - 结束计时,用时:{} 。", name, methodName, this.formatDuring(timer.interval()));

        } catch (Throwable e) {
            Console.error("【计时器@TimerLog】{}.{} - 方法出错,结束计时,用时:{} 毫秒,错误信息:{}。", name, methodName, timer.interval(), e.getMessage());
            e.printStackTrace();
        }
        return obj;
    }

    private String formatDuring(long mss) {

        long days = mss / (1000 * 60 * 60 * 24);

        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);

        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);

        long seconds = (mss % (1000 * 60)) / 1000;

        long msec = (mss % 1000);

        String msg = "";

        if(days > 0){
            msg += days + "天 ";
        }
        if(hours > 0){
            msg += hours + "时 ";
        }
        if(minutes > 0){
            msg += minutes + "分 ";
        }
        if(seconds > 0){
            msg += seconds + "秒 ";
        }
        if(msec > 0){
            msg += msec + "毫秒";
        }

        return msg;

    }

}

 

package com.base.common.aop;

import java.lang.annotation.*;

/**
 * @author Mr.Guan
 * @Title: 计时器
 * @Package ${package_name}
 * @Description: ${todo}
 * @Mail GuanWeiMail@163.com
 * @date 2018
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TimerLog {


    //增加参数,用来支持不同的业务

}

 

 

 

 

posted @ 2020-03-25 17:19  我是Superman  阅读(19)  评论(0)    收藏  举报