如何禁用 mongoDB Java 驱动程序日志记录?

2022-09-01 16:40:45

我正在尝试禁用 的日志输出。mongo-java-driver-3.0.0

在加载驱动程序之前,我尝试在应用程序开始时设置这些,但没有帮助。mongo

    // Enable MongoDB logging in general
    System.setProperty("DEBUG.MONGO", "false");

    // Enable DB operation tracing
    System.setProperty("DB.TRACE", "false");  

我收到这种日志:

11:01:15.406 [pool-1-thread-1] DEBUG org.mongodb.driver.protocol.query - Sending query of namespace susudev.Players on connection [connectionId{localValue:2, serverValue:28}] to server localhost:27017
11:01:15.406 [pool-1-thread-1] DEBUG org.mongodb.driver.protocol.query - Query completed

11:01:25.174 [cluster-ClusterId{value='554dbecb1b554f11e86c3a69', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Checking status of localhost:27017
11:01:25.177 [cluster-ClusterId{value='554dbecb1b554f11e86c3a69', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=STANDALONE, servers=[{address=localhost:27017, type=STANDALONE, roundTripTime=0.6 ms, state=CONNECTED}]

所以我的控制台完全挤满了mongo日志,我无法读取任何内容。


答案 1

要使这部分代码正常工作,您需要有Logback。(如果 maven 项目)

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>

然后,如果您只想禁用Mongo驱动程序日志记录,则应执行如下操作:

LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger rootLogger = loggerContext.getLogger("org.mongodb.driver");
rootLogger.setLevel(Level.OFF);

同样需要明确的是,以下是此代码工作的导入列表:

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;

此解决方案适用于 mongo java 驱动程序 3.0.0 和 ^。

编辑:这是一个级别设置为错误的衬里。

((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger("org.mongodb.driver").setLevel(Level.ERROR);

答案 2

如果需要动态方法,可以迭代记录器并设置其级别。或者,您可以手动设置级别。以下是 mongo 驱动程序记录器:

LogManager.getLogger("org.mongodb.driver.connection").setLevel(org.apache.log4j.Level.OFF);
LogManager.getLogger("org.mongodb.driver.management").setLevel(org.apache.log4j.Level.OFF);
LogManager.getLogger("org.mongodb.driver.cluster").setLevel(org.apache.log4j.Level.OFF);
LogManager.getLogger("org.mongodb.driver.protocol.insert").setLevel(org.apache.log4j.Level.OFF);
LogManager.getLogger("org.mongodb.driver.protocol.query").setLevel(org.apache.log4j.Level.OFF);
LogManager.getLogger("org.mongodb.driver.protocol.update").setLevel(org.apache.log4j.Level.OFF);