how to prevent logging on console when connected to mongodb from java?

前端 未结 4 1819
醉话见心
醉话见心 2021-01-04 10:25

I followed this mongodb documentation. Here is my code

public class JMongoDBCDemo
{
    MongoClient mongoClient;
    DB db;
    DBCollection coll;
    public         


        
相关标签:
4条回答
  • 2021-01-04 10:39

    Thanks to @jyemin By using MongoDB official documentation link

    Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
    mongoLogger.setLevel(Level.SEVERE); 
    

    Now no logs are there in the console.

    0 讨论(0)
  • 2021-01-04 10:39

    i tried this java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);

    it not worked, it still logs com.mongodb.diagnostics.logging.JULLogger log

    I changed it to JULLogger and it worked

    java.util.logging.Logger.getLogger("JULLogger").setLevel(Level.OFF);

    0 讨论(0)
  • 2021-01-04 10:47

    import your Mongo client through "com.mongodb.client.MongoClient"

    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoClients;
    
    import java.util.function.Consumer;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class Quick
    {
    
        public static void main(String[] args)
        {
            Logger.getLogger("org.mongodb.driver").setLevel(Level.WARNING);
            try (MongoClient mongo = MongoClients.create())
            {
                mongo.listDatabaseNames().forEach((Consumer<String>) System.out::println);
            }
        }
    }
    

    make sure you have the latest version of the driver, 3.12.2 at the time I wrote this answer

    <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.2</version>
    </dependency>
    

    if the above doesn't work, you're probably using a different logging module, look up how to turn that off, for example if you're using slf4j, create a file named "simpleLogger.properties" inside your resources folder and add this line to it

    org.slf4j.simpleLogger.defaultLogLevel = warn
    
    0 讨论(0)
  • 2021-01-04 10:49

    You could just use

    logging.level.org.mongodb.driver: ERROR
    
    0 讨论(0)
提交回复
热议问题