1. Introduzione
Spring Data MongoDB è silenzioso per default, il che va benissimo finché non serve sapere cosa sia arrivato davvero al server. Quando una query restituisce una forma inattesa, o semplicemente volete verificare i parametri e la collection coinvolta, la via più rapida per una risposta è alzare per un momento il livello di log.
Questa breve guida mostra l'unica impostazione che serve.
2. Abilitare il log delle query
Tutto l'accesso a MongoDB tramite Spring Data passa per MongoOperations, la cui implementazione di default è MongoTemplate. Quella singola classe è quindi l'interruttore da premere.
In una semplice applicazione Spring o Java, si configura al solito modo con il proprio backend di logging:
<logger name="org.springframework.data.mongodb.core.MongoTemplate" level="DEBUG" />
In Spring Boot, la stessa cosa va in application.properties:
logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
Se preferite lo YAML in application.yml, annidatelo così:
logging: level: org: springframework: data: mongodb: core: MongoTemplate: DEBUG
In alternativa, a livello di driver vero e proprio, si può attivare il log dei comandi con logging.level.org.mongodb.driver.protocol.command=DEBUG: è più verboso, ma mostra esattamente i comandi inviati al server.
3. Un test harness per vederlo in azione
Partiamo da un tipo di documento minimale:
@Document(collection = "book") public class Book { @MongoId private ObjectId id; private String bookName; private String authorName; // getters and setters }
Per non dipendere da un server condiviso, avviamo un MongoDB embedded per la durata dei test. Le due dipendenze necessarie sono:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> <version>${embed.mongo.version}</version> <scope>test</scope> </dependency>
La classe di test imposta la proprietà a livello di codice, così il livello DEBUG vale solo mentre la suite è in esecuzione:
@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 }
4. Come si presenta l'output
Con DEBUG attivo, ciascuno dei percorsi CRUD e di aggregazione più comuni registra qualcosa di utile.
4.1. Insert
Book book = new Book(); book.setBookName("Book"); book.setAuthorName("Author"); mongoTemplate.insert(book);
Si vede quali campi sono stati scritti e in quale collection, seguiti dalle letture di verifica che includono l'identificatore generato:
[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
4.2. Update
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);
Il log mostra il filtro e l'esatto payload $set:
[2022-03-20 17:48:31,759]-[main] DEBUG MongoTemplate - Calling update using query: { "bookName" : "Book"} and update: { "$set" : { "authorName" : "AuthorNameUpdate"}} in collection: book
4.3. Inserimento in blocco
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);
Viene riportata solo la dimensione del blocco:
[2022-03-20 17:52:00,564]-[main] DEBUG MongoTemplate - Inserting list of Documents containing 2 items
4.4. Remove
Book book = new Book(); book.setBookName("Book"); book.setAuthorName("Author"); mongoTemplate.insert(book); mongoTemplate.remove(book);
Le cancellazioni registrano l'identificatore usato per individuare il documento:
[2022-03-20 17:56:42,151]-[main] DEBUG MongoTemplate - Remove using query: { "_id" : { "$oid" : "62375cca2a2cba4db774d8c1"}} in collection: book.
4.5. Aggregazione
Le aggregazioni richiedono un tipo di risultato su cui mappare. Raggruppando per autore, per esempio:
public class GroupByAuthor { @Id private String authorName; private int authCount; // getters and setters }
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);
La pipeline stessa viene stampata, che è di gran lunga il modo più semplice per individuare un errore di raggruppamento:
[2022-03-20 17:58:51,237]-[main] DEBUG MongoTemplate - Executing aggregation: [{ "$group" : { "_id" : "$authorName", "authCount" : { "$sum" : 1}}}] in collection book
Ricordate di riportare il livello a INFO quando avete finito: l'output DEBUG su una collection molto trafficata è abbondante e può catturare contenuti dei documenti che preferireste non vedere nei file di log.