View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.mongodb4;
18  
19  import org.apache.logging.log4j.Logger;
20  import org.apache.logging.log4j.core.appender.AppenderLoggingException;
21  import org.apache.logging.log4j.core.appender.nosql.AbstractNoSqlConnection;
22  import org.apache.logging.log4j.core.appender.nosql.NoSqlConnection;
23  import org.apache.logging.log4j.core.appender.nosql.NoSqlObject;
24  import org.apache.logging.log4j.status.StatusLogger;
25  import org.bson.Document;
26  
27  import com.mongodb.ConnectionString;
28  import com.mongodb.MongoException;
29  import com.mongodb.client.MongoClient;
30  import com.mongodb.client.MongoCollection;
31  import com.mongodb.client.MongoDatabase;
32  import com.mongodb.client.model.CreateCollectionOptions;
33  import com.mongodb.client.result.InsertOneResult;
34  
35  /**
36   * The MongoDB implementation of {@link NoSqlConnection}.
37   */
38  public final class MongoDb4Connection extends AbstractNoSqlConnection<Document, MongoDb4DocumentObject> {
39  
40      private static final Logger LOGGER = StatusLogger.getLogger();
41  
42      private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
43              final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
44          try {
45              LOGGER.debug("Gettting collection '{}'...", collectionName);
46              // throws IllegalArgumentException if collectionName is invalid
47              final MongoCollection<Document> found = database.getCollection(collectionName);
48              LOGGER.debug("Got collection {}", found);
49              return found;
50          } catch (final IllegalStateException e) {
51              LOGGER.debug("Collection '{}' does not exist.", collectionName);
52              final CreateCollectionOptions options = new CreateCollectionOptions().capped(isCapped)
53                      .sizeInBytes(sizeInBytes);
54              LOGGER.debug("Creating collection '{}' with options {}...", collectionName, options);
55              database.createCollection(collectionName, options);
56              LOGGER.debug("Created collection.");
57              final MongoCollection<Document> created = database.getCollection(collectionName);
58              LOGGER.debug("Got created collection {}", created);
59              return created;
60          }
61  
62      }
63  
64      private final ConnectionString connectionString;
65      private final MongoCollection<Document> collection;
66      private final MongoClient mongoClient;
67  
68      public MongoDb4Connection(final ConnectionString connectionString, final MongoClient mongoClient,
69              final MongoDatabase mongoDatabase, final boolean isCapped, final Integer sizeInBytes) {
70          this.connectionString = connectionString;
71          this.mongoClient = mongoClient;
72          this.collection = getOrCreateMongoCollection(mongoDatabase, connectionString.getCollection(), isCapped,
73                  sizeInBytes);
74      }
75  
76      @Override
77      public void closeImpl() {
78          // LOG4J2-1196
79          mongoClient.close();
80      }
81  
82      @Override
83      public MongoDb4DocumentObject[] createList(final int length) {
84          return new MongoDb4DocumentObject[length];
85      }
86  
87      @Override
88      public MongoDb4DocumentObject createObject() {
89          return new MongoDb4DocumentObject();
90      }
91  
92      @Override
93      public void insertObject(final NoSqlObject<Document> object) {
94          try {
95              final Document unwrapped = object.unwrap();
96              LOGGER.debug("Inserting BSON Document {}", unwrapped);
97              InsertOneResult insertOneResult = this.collection.insertOne(unwrapped);
98              LOGGER.debug("Insert MongoDb result {}", insertOneResult);
99          } catch (final MongoException e) {
100             throw new AppenderLoggingException("Failed to write log event to MongoDB due to error: " + e.getMessage(),
101                     e);
102         }
103     }
104 
105     @Override
106     public String toString() {
107         return String.format("Mongo4Connection [connectionString=%s, collection=%s, mongoClient=%s]", connectionString,
108                 collection, mongoClient);
109     }
110 
111 }