0
点赞
收藏
分享

微信扫一扫

疫情防控交流社区平台——补充:统一记录日志(重点)

小黑Neo 2022-04-13 阅读 41

目录树

🌕统一记录日志

在这里插入图片描述

一、为什么要日志

二、AOP概念

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、AOP简单demo

3.1 AlphaAspect

@Component
@Aspect
public class AlphaAspect {

    //定义一个切入点
    @Pointcut("execution(* com.yty.community.service.*.*(..))") //范围:第一个*表示什么返回值都行,然后service包下所有的类,所有的方法,所有的参数
    public void pointcut(){

    }

    @Before("pointcut()")
    public void before(){
        System.out.println("before");
    }

    @After("pointcut()")
    public void after(){
        System.out.println("after");
    }

    @AfterReturning("pointcut()")
    public void afterReturning(){
        System.out.println("afterReturning");
    }

    @AfterThrowing("pointcut()")
    public void afterThrowing(){
        System.out.println("afterThrowing");
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("around before");
        Object obj = joinPoint.proceed();
        System.out.println("around after");
        return obj;
    }

}

3.2 测试

启动项目,并clear all 控制台,然后访问首页index
在这里插入图片描述
没有抛出这个:
在这里插入图片描述
是因为还没报错,报错就回抛,这里不试了。

四、⭐️统一记录日志

4.1 ServiceLogAspect

@Component
@Aspect
public class ServiceLogAspect {

    //因为要记日志,所以实例化一个log/或者直接使用后@Sl4j注解
    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    //1.声明切点
    @Pointcut("execution(* com.yty.community.service.*.*(..))") //范围:第一个*表示什么返回值都行,然后service包下所有的类,所有的方法,所有的参数
    public void pointcut(){

    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //格式: 用户[1.2.3.4],在[xxxTime],访问了[com.yty.community.service.xxx()]
        //要想获取这么一个格式,用户ip怎么获取?可通过request获取,但是这个方法里怎么去获取request对象呢,不能直接声明一个request对象,而是利用工具类,然后直接获取request了
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //访问的是某个类某个方法,怎么知道我访问的是哪个类那个方法呢 —— 加一个参数JointPoint
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName();

        logger.info(String.format("用户[%s],在[%s],访问了[%s].",  ip,now,target));
    }

}

在这里插入图片描述

4.2 测试

进入首页
在这里插入图片描述
然后看后台控制器:

在这里插入图片描述
改成127.0.0.1.后的控制台:
在这里插入图片描述

举报

相关推荐

0 条评论