java 日志管理 @Aspect

@Aspect  Spring 统一日志管理 详见 http://www.cnblogs.com/chihirotan/p/6228337.html
在pom.xml文件中配置
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

定义一个类,命名LogAspect,在saveSysLog中执行具体要保存内容操作,ILog 是之前自定义的接口注释,例子中有获取ILog内容、网址ip、请求参数等内容

@Aspect
@Component
public class LogAspect {

    @Pointcut("@annotation(com.example.demo.common.annotation.ILog)")
    public void saveLogCut(){
    }
    /**
     * 切面记录系统日志
     */
    @Around("saveLogCut()")//
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //保存日志
        saveSysLog(point, time);
        return result;
    }
    void saveSysLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException     
       {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ILog syslog = method.getAnnotation(ILog.class);
        if (syslog != null) {
            // 注解上的描述
            sysLog.setOperation(syslog.value());
        }
          // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
         // 请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = new Gson().toJson(args[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }

          // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
         //ip 
        String ip=IPUtils.getIpAddr(request)
    }
}

切面方法说明:
 @Aspect -- 作用是把当前类标识为一个切面供容器读取
@Pointcut -- (切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
@Before -- 标识一个前置增强方法,相当于BeforeAdvice的功能
@AfterReturning -- 后置增强,相当于AfterReturningAdvice,方法退出时执行
@AfterThrowing -- 异常抛出增强,相当于ThrowsAdvice
@After -- final增强,不管是抛出异常或者正常退出都会执行
@Around -- 环绕增强,相当于MethodInterceptor 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值