热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

Springboot的日志管理springboot无需引入日志的包,springboot默认已经依赖了slf4j、logback、log4j等日志。我习惯用slf4j,下面就用sl

==============Springboot的日志管理=============

  springboot无需引入日志的包,springboot默认已经依赖了slf4j、logback、log4j等日志。我习惯用slf4j,下面就用slf4j做配置。

如果你导入了spring-boot-starter-web,这个会自动依赖上述日志。如下依赖:

Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

 

0.日志测试类:

package daoTest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.qlq.MySpringBootApplication;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class PlainTest {
    private static final Logger logger = LoggerFactory.getLogger(PlainTest.class);

    @Test
    public void findAll() {
        logger.error("error , msg->{} ", "错误");
        logger.info("info , msg->{} ", "信息");
    }
}

 

1.springboot默认的日志级别是debug

 Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

 

2.如果需要修改日志的相关配置可以修改applications.properties文件

############################################################
#
# 日志相关配置(默认集成的有slf4j,Logback等)
#
############################################################
#指定配置文件的位置,只能是xml或者groovy结尾
#logging.cOnfig=classpath:logback.xml
#默认的日志级别
logging.level.root=INFO
# mapper 接口所在的包设置为 debug
logging.level.cn.qlq.mapper=DEBUG
#生成日志文件的位置
logging.file=G:/springboot.log
#生成日志文件的目录,名称默认为spring.log
#logging.path=e:/
#指定日志的格式
#logging.pattern.cOnsole=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %clr(%logger){cyan} %clr(%msg%n){green}
#logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

     解释:上面logging.level.root可以指定所以包默认的日志级别,logging.level.cn.qlq.mapper是对单独的子包设定日志级别,其级别可低于上面的root,也可以高于root

    logging.file是指定文件日志的输出位置以及名称,logging.path是指定日志文件的位置,默认名称是spring.log(如果两者都配置以logging.file生效)

    最后面是指定控制台和输出文件的日志格式。

    logging.config是指定配置文件的位置,只能是xml或者groovy结尾。

 

  关于日志级别等大致相同,参考:https://www.cnblogs.com/qlqwjy/p/9275415.html

==============Springboot整合Junit测试=============

Springboot中我们也可以像在普通的SSM环境中进行SpringJunit测试。

1.引入测试需要的模块

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

2.建立测试目录,一般在src/test/java下面和src/test/resources目录下

  mapper文件和配置文件要复制到src/test/resources目录下。

Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

3.建立测试类进行测试

  SpringBootTest的classes是springboot项目启动的运行类,也就是带有@SpringBootApplication的类。

package daoTest;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.qlq.MySpringBootApplication;
import cn.qlq.bean.User;
import cn.qlq.mapper.UserMapper;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class PlainTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void findAll() {
        List findAll = userMapper.findAll();
        System.out.println(findAll);
    }
}

 

==============Springboot的AOP整合=============

  springboot整合Aop非常简单,只用引入AOP模块的依赖即可。然后就可以使用注解AOP。

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>

 

1.AOP的第一种切入方式:基于切点表达式进行拦截

  如下记录servcice层的所有方法的执行时间的AOP写法

package cn.qlq.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 记录service层执行时间的AOP切面
 * 
 * @author QiaoLiQiang
 * @time 2019年2月21日下午9:20:15
 */
@Aspect
@Component
public class LogServiceTakeTime {
    private final static Logger log = LoggerFactory.getLogger(LogServiceTakeTime.class);

    @Pointcut("execution(* cn.qlq.service..*.*(..))")
    public void performance() {
    }

    /**
     * 环绕通知记录时间
     * 
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("performance()")
    public Object doLog(ProceedingJoinPoint joinPoint) throws Throwable {

        // 记录起始时间
        long begin = System.currentTimeMillis();
        Object result = "";
        /** 执行目标方法 */
        try {
            result = joinPoint.proceed();
        } catch (Exception e) {
            log.error("日志记录发生错误, errorMessage: {}", e.getMessage());
        } finally {
            /** 记录操作时间 */
            long took = (System.currentTimeMillis() - begin) / 1000;
            log.info("Service执行时间为: {}秒", took);
        }
        return result;
    }

    /**
     * 前置通知
     * 
     * @param joinPoint
     * @throws Throwable
     */
    @Before("performance()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        log.info("doBefore");
    }

}

 

2.第二种切入方式:基于注解

(1)编写注解

package cn.qlq.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解
 * 
 * @author QiaoLiQiang
 * @time 2019年2月21日下午9:45:17
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogAnnotation {
    String operateDescription();// 记录日志的操作类型,不写默认值就是一个必须填的注解
}

 

(2)编写切面进行拦截:一般在环绕通知中处理足够了

package cn.qlq.aspect;

import java.lang.reflect.Method;
import java.sql.SQLException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.qlq.annotation.MyLogAnnotation;

/**
 * @Author: qlq
 * @Description 日志记录切面(拦截自定义注解进行日志记录)
 * @Date: 11:46 2018/5/14
 */
@Component
@Aspect
public class MyLogAspect {
    private final static Logger log = LoggerFactory.getLogger(MyLogAspect.class);

    /**
     * 环绕通知处理
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cn.qlq.annotation.MyLogAnnotation)")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        // 1.方法执行前的处理,相当于前置通知
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        // 获取方法上面的注解
        MyLogAnnotation logAnno = method.getAnnotation(MyLogAnnotation.class);
        // 获取到类名
        String targetName = pjp.getTarget().getClass().getName();
        // 获取到方法名字
        String methodName = method.getName();
        // 获取操作描述的属性值
        String operateDescription = logAnno.operateDescription();
        Object result = null;
        try {
            // 让代理方法执行
            result = pjp.proceed();
            // 2.相当于后置通知(方法成功执行之后走这里)
        } catch (SQLException e) {
            // 3.相当于异常通知部分
        } finally {
            // 4.相当于最终通知
            log.info("class->{},methodName->{},operateDescription->{}", targetName, methodName, operateDescription);
        }
        return result;
    }
}

(3)测试:

Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

 

结果:

Springboot的日志管理&Springboot整合Junit测试&Springboot中AOP的使用

 

   关于AOP在之前也研究过了,在这里就只研究其使用,具体的使用方法参考:https://www.cnblogs.com/qlqwjy/p/8729280.html                               https://www.cnblogs.com/qlqwjy/p/8747476.html

 


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • 本文介绍了在多平台下进行条件编译的必要性,以及具体的实现方法。通过示例代码展示了如何使用条件编译来实现不同平台的功能。最后总结了只要接口相同,不同平台下的编译运行结果也会相同。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • (三)多表代码生成的实现方法
    本文介绍了一种实现多表代码生成的方法,使用了java代码和org.jeecg框架中的相关类和接口。通过设置主表配置,可以生成父子表的数据模型。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文介绍了包的基础知识,包是一种模块,本质上是一个文件夹,与普通文件夹的区别在于包含一个init文件。包的作用是从文件夹级别组织代码,提高代码的维护性。当代码抽取到模块中后,如果模块较多,结构仍然混乱,可以使用包来组织代码。创建包的方法是右键新建Python包,使用方式与模块一样,使用import来导入包。init文件的使用是将文件夹变成一个模块的方法,通过执行init文件来导入包。一个包中通常包含多个模块。 ... [详细]
author-avatar
try
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有