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