简体   繁体   English

为 MongoDB Java 驱动程序配置日志记录

[英]Configure logging for the MongoDB Java driver

Can I configure the MongoDB Java driver to output useful (for debugging) messages, ideally using one of the standard logging frameworks?我可以将 MongoDB Java 驱动程序配置为输出有用的(用于调试)消息,最好使用标准日志记录框架之一吗? I'd mainly be interested in seeing each query that goes out, how much data was received and how long it took, as well as any error codes.我主要对查看发出的每个查询、收到的数据量和花费的时间以及任何错误代码感兴趣。

You need to set a couple of system properties before loading any of the MongoDB Java driver classes:加载任何 MongoDB Java 驱动程序类之前,您需要设置几个系统属性:

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

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

After doing that the driver will use the standard Java logging framework to log messages.之后,驱动程序将使用 标准的 Java 日志框架来记录消息。

Unfortunately, as far as I can tell from the Java driver code, the logging granularity is not all that fine - for example you cannot selectively log operations on a specific collection.不幸的是,据我从 Java 驱动程序代码中可以看出,日志记录的粒度并不是那么好——例如,您不能有选择地记录特定集合上的操作。

Anyone still facing this problem with new version mongodb driver 3.x?使用新版本 mongodb 驱动程序 3.x 的人仍然面临这个问题吗?

define a logger for mongo driver package in log4j.propertieslog4j.properties 中为 mongo 驱动程序包定义一个记录器

log4j.logger.org.mongodb.driver=INFO

com.mongodb has changed to org.mongodb . com.mongodb已更改为org.mongodb

Another way to do set MongoDB's log level:另一种设置 MongoDB 日志级别的方法:

import java.util.logging.Logger;
Logger mongoLogger = Logger.getLogger( "com.mongodb" );
mongoLogger.setLevel(Level.SEVERE); // e.g. or Log.WARNING, etc.

You don't have to do this before using any of the driver classes, you can set/change log levels at any time.在使用任何驱动程序类之前,您不必这样做,您可以随时设置/更改日志级别。

Following line works for me,以下线路对我有用,

import java.util.logging.Logger;
import java.util.logging.Level;

Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
mongoLogger.setLevel(Level.SEVERE); // e.g. or Log.WARNING, etc.

To log all queries with the 3.6 MongoDB Java driver or later:要使用 3.6 MongoDB Java 驱动程序或更高版本记录所有查询:

  1. Make sure you are using slf4j确保您使用的是 slf4j

     <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.29</version> </dependency>

    or if you are using log4j2或者如果您使用的是 log4j2

     <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.13.0</version> </dependency>
  2. Set the logging level for org.mongodb.driver to DEBUGorg.mongodb.driver的日志级别设置为DEBUG

    So for log4j2 you would need to add something like this to the xml configuration file因此,对于 log4j2,您需要在 xml 配置文件中添加类似的内容

    <logger name="org.mongodb.driver" level="DEBUG"></logger>

Setting the log level to INFO or SEVERE level as suggested in other answers didn't work for me.按照其他答案中的建议将日志级别设置为 INFO 或 SEVERE 级别对我不起作用。 According to the MongoDB specification if slf4j is not present then根据MongoDB 规范,如果 slf4j 不存在,则

the driver will fall back to JUL (java.util.logging)驱动程序将回退到 JUL (java.util.logging)

which is what most other answers use, so perhaps that uses different log levels (although I can't imagine that's the case)这是大多数其他答案使用的,所以也许使用不同的日志级别(尽管我无法想象是这种情况)

As of 3.11 beta2 this worked for me从 3.11 beta2 开始,这对我有用

import com.mongodb.diagnostics.logging.Loggers;

import java.util.logging.Level;
import java.util.logging.Logger;


Logger.getLogger(Loggers.PREFIX).setLevel(Level.SEVERE);

Mongodb team offer one solution ( https://mongodb.github.io/mongo-java-driver/3.11/driver/reference/monitoring/ ). Mongodb 团队提供了一种解决方案( https://mongodb.github.io/mongo-java-driver/3.11/driver/reference/monitoring/ )。

We can implement ConnectionPoolListener and put in when we create MongoClient .我们可以实现ConnectionPoolListener并在我们创建MongoClientMongoClient

For example (with log4j) :例如(使用 log4j):

public class ConnectionPoolListenerMongoDb implements ConnectionPoolListener {
private static final Logger logger = Logger.getLogger(StatisticsDaoImpl.class);

@Override
public void connectionPoolOpened(ConnectionPoolOpenedEvent connectionPoolOpenedEvent) {
    logger.info(connectionPoolOpenedEvent.toString());
}

@Override
public void connectionPoolClosed(ConnectionPoolClosedEvent connectionPoolClosedEvent) {
    logger.info(connectionPoolClosedEvent.toString());
}

@Override
public void connectionCheckedOut(ConnectionCheckedOutEvent connectionCheckedOutEvent) {
    logger.info(connectionCheckedOutEvent.toString());
}

@Override
public void connectionCheckedIn(ConnectionCheckedInEvent connectionCheckedInEvent) {
    logger.info(connectionCheckedInEvent.toString());
}

@Override
public void waitQueueEntered(ConnectionPoolWaitQueueEnteredEvent connectionPoolWaitQueueEnteredEvent) {
    logger.info(connectionPoolWaitQueueEnteredEvent.toString());
}

@Override
public void waitQueueExited(ConnectionPoolWaitQueueExitedEvent connectionPoolWaitQueueExitedEvent) {
    logger.info(connectionPoolWaitQueueExitedEvent.toString());
}

@Override
public void connectionAdded(ConnectionAddedEvent connectionAddedEvent) {
    logger.info(connectionAddedEvent.toString());
}

@Override
public void connectionRemoved(ConnectionRemovedEvent connectionRemovedEvent) {
    logger.info(connectionRemovedEvent.toString());
}
}

Settings :设置:

    private MongoClientSettings getMongoClientSettings() throws IOException {
    return MongoClientSettings.builder()
                    .applyToConnectionPoolSettings(new Block<ConnectionPoolSettings.Builder>() {
                        @Override
                        public void apply(ConnectionPoolSettings.Builder builder) {
                            builder.addConnectionPoolListener(new ConnectionPoolListenerMongoDb());
                        }
                    })
                    .applyConnectionString(new ConnectionString(Settings.getMongoSettings()))
                    .build();
}

Creation :创作:

MongoClientSettings settings = getMongoClientSettings();
        mongoClient = MongoClients.create(settings);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM