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.mongodb3;
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.MongoClient;
28  import com.mongodb.MongoException;
29  import com.mongodb.client.MongoCollection;
30  import com.mongodb.client.MongoDatabase;
31  import com.mongodb.client.model.CreateCollectionOptions;
32  
33  /**
34   * The MongoDB implementation of {@link NoSqlConnection}.
35   */
36  public final class MongoDbConnection extends AbstractNoSqlConnection<Document, MongoDbDocumentObject> {
37  
38      private static final Logger LOGGER = StatusLogger.getLogger();
39  
40      private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
41              final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
42          try {
43              LOGGER.debug("Gettting collection '{}'...", collectionName);
44              // throws IllegalArgumentException if collectionName is invalid
45              return database.getCollection(collectionName);
46          } catch (final IllegalStateException e) {
47              LOGGER.debug("Collection '{}' does not exist.", collectionName);
48              final CreateCollectionOptions options = new CreateCollectionOptions()
49              // @formatter:off
50                      .capped(isCapped)
51                      .sizeInBytes(sizeInBytes);
52              // @formatter:on
53              LOGGER.debug("Creating collection {} (capped = {}, sizeInBytes = {})", collectionName, isCapped,
54                      sizeInBytes);
55              database.createCollection(collectionName, options);
56              return database.getCollection(collectionName);
57          }
58  
59      }
60  
61      private final MongoCollection<Document> collection;
62      private final MongoClient mongoClient;
63  
64      public MongoDbConnection(final MongoClient mongoClient, final MongoDatabase mongoDatabase,
65              final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
66          this.mongoClient = mongoClient;
67          this.collection = getOrCreateMongoCollection(mongoDatabase, collectionName, isCapped, sizeInBytes);
68      }
69  
70      @Override
71      public void closeImpl() {
72          // LOG4J2-1196
73          mongoClient.close();
74      }
75  
76      @Override
77      public MongoDbDocumentObject[] createList(final int length) {
78          return new MongoDbDocumentObject[length];
79      }
80  
81      @Override
82      public MongoDbDocumentObject createObject() {
83          return new MongoDbDocumentObject();
84      }
85  
86      @Override
87      public void insertObject(final NoSqlObject<Document> object) {
88          try {
89              final Document unwrapped = object.unwrap();
90              LOGGER.debug("Inserting object {}", unwrapped);
91              this.collection.insertOne(unwrapped);
92          } catch (final MongoException e) {
93              throw new AppenderLoggingException("Failed to write log event to MongoDB due to error: " + e.getMessage(),
94                      e);
95          }
96      }
97  
98  }