• 使用Spring Boot 记录 MongoDB查询 日志(Log)


    1. 概述

    在使用 Spring Data MongoDB 时,我们可能需要将日志记录到比默认级别更高的级别。通常,我们可能需要查看一些附加信息,例如语句执行或查询参数。

    在这个简短的教程中,我们将看到如何修改查询的 MongoDB 日志记录级别。

    2. 配置MongoDB查询日志

    MongoDB Support提供了MongoOperations接口或其主要的MongoTemplate实现来访问数据,所以我们只需要为MongoTemplate类配置一个 调试(debug)级别

    像任何 Spring 或 Java 应用程序一样,我们可以使用 日志库 并为MongoTemplate定义日志级别。

    通常,我们可以在配置文件中写入如下内容:

    <logger name="org.springframework.data.mongodb.core.MongoTemplate" level="DEBUG" />
    
    • 1

    但是,如果我们正在运行Spring Boot应用程序,我们可以在application.properties文件中进行配置:

    logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
    
    • 1

    同样,我们可以使用YAML语法:

    logging:
      level:
        org:
          springframework:
            data:
              mongodb:
                core:
                  MongoTemplate: DEBUG
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3. 日志测试类

    首先,让我们创建一个Book类:

    @Document(collection = "book")
    public class Book {
    
        @MongoId
        private ObjectId id;
        private String bookName;
        private String authorName;
    
        // getters and setters
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    我们想创建一个简单的测试类并检查日志。

    为了证明这一点,我们使用Embedded MongoDB。可以肯定的是,让我们首先检查我们的依赖项:

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-mongodbartifactId>
    dependency>
    <dependency>
        <groupId>de.flapdoodle.embedgroupId>
        <artifactId>de.flapdoodle.embed.mongoartifactId>
        <version>${embed.mongo.version}version>
        <scope>testscope>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    最后,让我们使用Spring Boot Test定义我们的测试类:

    @SpringBootTest
    @TestPropertySource(properties = { "logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG" })
    public class LoggingUnitTest {
    
        private static final String CONNECTION_STRING = "mongodb://%s:%d";
    
        private MongodExecutable mongodExecutable;
        private MongoTemplate mongoTemplate;
    
        @AfterEach
        void clean() {
            mongodExecutable.stop();
        }
    
        @BeforeEach
        void setup() throws Exception {
            String ip = "localhost";
            int port = 27017;
    
            ImmutableMongodConfig mongodbConfig = MongodConfig.builder()
              .version(Version.Main.PRODUCTION)
              .net(new Net(ip, port, Network.localhostIsIPv6()))
              .build();
    
            MongodStarter starter = MongodStarter.getDefaultInstance();
            mongodExecutable = starter.prepare(mongodbConfig);
            mongodExecutable.start();
            mongoTemplate = new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, ip, port)), "test");
        }
        // tests
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    4. 日志样例

    在本节中,我们将定义一些简单的测试用例并显示相关日志以测试最常见的场景,例如查找、插入、更新或聚合Document

    4.1. 插入

    首先,让我们从插入一个Document开始:

    Book book = new Book();
    book.setBookName("Book");
    book.setAuthorName("Author");
    
    mongoTemplate.insert(book);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    日志显示我们正在插入哪个集合。查找Document时,还会记录 id:

    [2022-03-20 17:42:47,093]-[main] DEBUG MongoTemplate - Inserting Document containing fields: [bookName, authorName, _class] in collection: book
    ...
    [2022-03-20 17:42:47,144]-[main] DEBUG MongoTemplate - findOne using query: { "id" : { "$oid" : "623759871ff6275fe96a5ecb"}} fields: Document{{}} for class: class com.baeldung.mongodb.models.Book in collection: book
    [2022-03-20 17:42:47,149]-[main] DEBUG MongoTemplate - findOne using query: { "_id" : { "$oid" : "623759871ff6275fe96a5ecb"}} fields: {} in db.collection: test.book
    
    • 1
    • 2
    • 3
    • 4

    4.2. 更新

    同样,在更新Document时:

    Book book = new Book();
    book.setBookName("Book");
    book.setAuthorName("Author");
    
    mongoTemplate.insert(book);
    
    String authorNameUpdate = "AuthorNameUpdate";
    
    book.setAuthorName(authorNameUpdate);
    mongoTemplate.updateFirst(query(where("bookName").is("Book")), update("authorName", authorNameUpdate), Book.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    我们可以在日志中看到实际更新的Document字段:

    [2022-03-20 17:48:31,759]-[main] DEBUG MongoTemplate - Calling update using query: { "bookName" : "Book"} and update: { "$set" : { "authorName" : "AuthorNameUpdate"}} in collection: book
    
    • 1

    4.3. 批量插入

    让我们添加一个批量插入的示例:

    Book book = new Book();
    book.setBookName("Book");
    book.setAuthorName("Author");
    
    Book book1 = new Book();
    book1.setBookName("Book1");
    book1.setAuthorName("Author1");
    
    mongoTemplate.insert(Arrays.asList(book, book1), Book.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    我们可以在日志中看到插入的Document数量:

    [2022-03-20 17:52:00,564]-[main] DEBUG MongoTemplate - Inserting list of Documents containing 2 items
    
    • 1

    4.4. 删除

    另外,让我们添加一个删除示例:

    Book book = new Book();
    book.setBookName("Book");
    book.setAuthorName("Author");
    
    mongoTemplate.insert(book);
    
    mongoTemplate.remove(book);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    我们可以在日志中看到,在这种情况下,删除Document的 id :

    [2022-03-20 17:56:42,151]-[main] DEBUG MongoTemplate - Remove using query: { "_id" : { "$oid" : "62375cca2a2cba4db774d8c1"}} in collection: book.
    
    • 1

    4.5. 聚合

    让我们看一个Aggregation的例子。在这种情况下,我们需要定义一个结果类。例如,我们将按作者姓名聚合:

    public class GroupByAuthor {
    
        @Id
        private String authorName;
        private int authCount;
    
        // getters and setters
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    接下来,让我们定义一个用于分组的测试用例:

    Book book = new Book();
    book.setBookName("Book");
    book.setAuthorName("Author");
    
    Book book1 = new Book();
    book1.setBookName("Book1");
    book1.setAuthorName("Author");
    
    Book book2 = new Book();
    book2.setBookName("Book2");
    book2.setAuthorName("Author");
    
    mongoTemplate.insert(Arrays.asList(book, book1, book2), Book.class);
    
    GroupOperation groupByAuthor = group("authorName")
      .count()
      .as("authCount");
    
    Aggregation aggregation = newAggregation(groupByAuthor);
    
    AggregationResults<GroupByAuthor> aggregationResults = mongoTemplate.aggregate(aggregation, "book", GroupByAuthor.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    我们可以在日志中看到我们聚合了哪个字段以及什么样的聚合管道:

    [2022-03-20 17:58:51,237]-[main] DEBUG MongoTemplate - Executing aggregation: [{ "$group" : { "_id" : "$authorName", "authCount" : { "$sum" : 1}}}] in collection book
    
    • 1

    5. 结论

    在本文中,我们研究了如何为 Spring Data MongoDB 启用调试日志记录级别。

    我们定义了一些常见的查询场景,并在进行一些实时测试时查看了它们的相关日志。

  • 相关阅读:
    大神之路-起始篇 | 第1章.计算机科学导论之【基础绪论】学习笔记
    MDK工程转换Vscode+EIDE方法
    flex布局入门讲解
    【WSL】【Opencv】【MNN】【C++】在windows中使用WSL开发C++程序的环境搭建
    一文带你认知定时消息发布RocketMQ
    安装MPICH并运行第一行代码
    【JAVA】面向对象的编程语言(继承篇)
    移植 simpleFoc笔记(一)
    3.流的输入/输出
    算法系列五:十大经典排序算法之——选择排序
  • 原文地址:https://blog.csdn.net/wjw465150/article/details/127800341