Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions log4j-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -150,9 +149,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>

<dependencies>

<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/
package org.apache.logging.log4j.mongodb;

import com.mongodb.ConnectionString;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
Expand Down Expand Up @@ -59,20 +58,17 @@ private static MongoCollection<Document> getOrCreateMongoCollection(
}
}

private final ConnectionString connectionString;
private final MongoCollection<Document> collection;
private final MongoClient mongoClient;

public MongoDbConnection(
final ConnectionString connectionString,
final MongoClient mongoClient,
final MongoDatabase mongoDatabase,
final String collectionName,
final boolean isCapped,
final Long sizeInBytes) {
this.connectionString = connectionString;
this.mongoClient = mongoClient;
this.collection =
getOrCreateMongoCollection(mongoDatabase, connectionString.getCollection(), isCapped, sizeInBytes);
this.collection = getOrCreateMongoCollection(mongoDatabase, collectionName, isCapped, sizeInBytes);
}

@Override
Expand Down Expand Up @@ -106,8 +102,6 @@ public void insertObject(final NoSqlObject<Document> object) {

@Override
public String toString() {
return String.format(
"Mongo4Connection [connectionString=%s, collection=%s, mongoClient=%s]",
connectionString, collection, mongoClient);
return String.format("Mongo4Connection [collection=%s, mongoClient=%s]", collection, mongoClient);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoNamespace;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
Expand Down Expand Up @@ -54,9 +55,45 @@ public static class Builder<B extends Builder<B>> extends AbstractFilterable.Bui
@PluginAttribute("capped")
private boolean capped = false;

@PluginAttribute("collectionName")
private String collectionName;

@PluginAttribute("databaseName")
private String databaseName;

@Override
public MongoDbProvider build() {
return new MongoDbProvider(connectionStringSource, capped, collectionSize);

LOGGER.debug("Creating ConnectionString {}...", connectionStringSource);
final ConnectionString connectionString;
try {
connectionString = new ConnectionString(connectionStringSource);
} catch (final IllegalArgumentException exception) {
final String message = String.format("Invalid MongoDB connection string `%s`.", connectionStringSource);
throw new IllegalArgumentException(message, exception);
}

// Validate the provided databaseName property
final String effectiveDatabaseName = databaseName != null ? databaseName : connectionString.getDatabase();
try {
MongoNamespace.checkDatabaseNameValidity(effectiveDatabaseName);
} catch (final IllegalArgumentException exception) {
final String message = String.format("Invalid MongoDB database name `%s`.", effectiveDatabaseName);
throw new IllegalArgumentException(message, exception);
}

// Validate the provided collectionName property
final String effectiveCollectionName =
collectionName != null ? collectionName : connectionString.getCollection();
try {
MongoNamespace.checkCollectionNameValidity(effectiveCollectionName);
} catch (final IllegalArgumentException exception) {
final String message = String.format("Invalid MongoDB collection name `%s`.", effectiveCollectionName);
throw new IllegalArgumentException(message, exception);
}

return new MongoDbProvider(
connectionString, capped, collectionSize, effectiveDatabaseName, effectiveCollectionName);
}

public B setConnectionStringSource(final String connectionStringSource) {
Expand All @@ -73,6 +110,16 @@ public B setCollectionSize(final long collectionSize) {
this.collectionSize = collectionSize;
return asBuilder();
}

public B setCollectionName(final String collectionName) {
this.collectionName = collectionName;
return asBuilder();
}

public B setDatabaseName(final String databaseName) {
this.databaseName = databaseName;
return asBuilder();
}
}

private static final Logger LOGGER = StatusLogger.getLogger();
Expand All @@ -94,47 +141,54 @@ public static <B extends Builder<B>> B newBuilder() {

private final Long collectionSize;
private final boolean isCapped;
private final String collectionName;
private final MongoClient mongoClient;
private final MongoDatabase mongoDatabase;
private final ConnectionString connectionString;

private MongoDbProvider(final String connectionStringSource, final boolean isCapped, final Long collectionSize) {
LOGGER.debug("Creating ConnectionString {}...", connectionStringSource);
this.connectionString = new ConnectionString(connectionStringSource);
private MongoDbProvider(
final ConnectionString connectionString,
final boolean isCapped,
final Long collectionSize,
final String databaseName,
final String collectionName) {

LOGGER.debug("Created ConnectionString {}", connectionString);
this.connectionString = connectionString;
LOGGER.debug("Creating MongoClientSettings...");
// @formatter:off
final MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(this.connectionString)
.applyConnectionString(connectionString)
.codecRegistry(CODEC_REGISTRIES)
.build();
// @formatter:on
LOGGER.debug("Created MongoClientSettings {}", settings);
LOGGER.debug("Creating MongoClient {}...", settings);
this.mongoClient = MongoClients.create(settings);
LOGGER.debug("Created MongoClient {}", mongoClient);
final String databaseName = this.connectionString.getDatabase();
LOGGER.debug("Getting MongoDatabase {}...", databaseName);
this.mongoDatabase = this.mongoClient.getDatabase(databaseName);
LOGGER.debug("Got MongoDatabase {}", mongoDatabase);
this.collectionName = collectionName;
this.isCapped = isCapped;
this.collectionSize = collectionSize;
}

@Override
public MongoDbConnection getConnection() {
return new MongoDbConnection(connectionString, mongoClient, mongoDatabase, isCapped, collectionSize);
return new MongoDbConnection(mongoClient, mongoDatabase, collectionName, isCapped, collectionSize);
}

@Override
public String toString() {
return String.format(
"%s [connectionString=%s, collectionSize=%s, isCapped=%s, mongoClient=%s, mongoDatabase=%s]",
"%s [connectionString=%s, collectionSize=%s, isCapped=%s, mongoClient=%s, mongoDatabase=%s, collectionName=%s]",
MongoDbProvider.class.getSimpleName(),
connectionString,
collectionSize,
isCapped,
mongoClient,
mongoDatabase);
mongoDatabase,
collectionName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.mongodb;

import com.mongodb.client.MongoClient;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

@UsingMongoDb
@LoggerContextSource("MongoDbCollectionNameIT.xml")
// Print debug status logger output upon failure
@UsingStatusListener
class MongoDbCollectionNameIT extends AbstractMongoDbCappedIT {

@Test
@Override
protected void test(final LoggerContext ctx, final MongoClient mongoClient) {
super.test(ctx, mongoClient);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.mongodb;

import com.mongodb.client.MongoClient;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
import org.junit.jupiter.api.Test;

@UsingMongoDb
@LoggerContextSource("MongoDbDatabaseAndCollectionNameIT.xml")
// Print debug status logger output upon failure
@UsingStatusListener
class MongoDbDatabaseAndCollectionNameIT extends AbstractMongoDbCappedIT {

@Test
@Override
protected void test(final LoggerContext ctx, final MongoClient mongoClient) {
super.test(ctx, mongoClient);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.mongodb;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import com.mongodb.MongoNamespace;
import com.mongodb.client.MongoCollection;
import java.lang.reflect.Field;
import org.bson.Document;
import org.junit.jupiter.api.Test;

class MongoDbProviderTest {

private static final String CS_WO_DB = "mongodb://localhost:27017";
private static final String CS_W_DB = "mongodb://localhost:27017/logging";
private static final String CS_W_DB_N_COLL = "mongodb://localhost:27017/logging.logs";

private static final String COLL_NAME = "logsTest";
private static final String DB_NAME = "loggingTest";

@Test
void createProviderWithDatabaseAndCollectionProvidedViaConfig() {
final MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(CS_WO_DB)
.setDatabaseName(DB_NAME)
.setCollectionName(COLL_NAME)
.build();
assertNotNull(provider);
final MongoNamespace namespace = getNamespace(provider.getConnection());
assertEquals(COLL_NAME, namespace.getCollectionName());
assertEquals(DB_NAME, namespace.getDatabaseName());
}

@Test
void createProviderWithoutDatabaseName() {
final MongoDbProvider provider =
MongoDbProvider.newBuilder().setConnectionStringSource(CS_WO_DB).build();
assertNull(provider);
}

@Test
void createProviderWithoutDatabaseNameWithCollectionName() {
final MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(CS_WO_DB)
.setCollectionName(COLL_NAME)
.build();
assertNull(provider);
}

@Test
void createProviderWithoutCollectionName() {
final MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(CS_WO_DB)
.setDatabaseName(DB_NAME)
.build();
assertNull(provider);
}

@Test
void createProviderWithDatabaseOnConnectionString() {
final MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(CS_W_DB)
.setCollectionName(COLL_NAME)
.build();
assertNotNull(provider);
final MongoNamespace namespace = getNamespace(provider.getConnection());
assertEquals(COLL_NAME, namespace.getCollectionName());
assertEquals("logging", namespace.getDatabaseName());
}

@Test
void createProviderConfigOverridesConnectionString() {
final MongoDbProvider provider = MongoDbProvider.newBuilder()
.setConnectionStringSource(CS_W_DB_N_COLL)
.setCollectionName(COLL_NAME)
.setDatabaseName(DB_NAME)
.build();
assertNotNull(provider);
final MongoNamespace namespace = getNamespace(provider.getConnection());
assertEquals(COLL_NAME, namespace.getCollectionName());
assertEquals(DB_NAME, namespace.getDatabaseName());
}

private static MongoNamespace getNamespace(final MongoDbConnection connection) {
try {
final Field collectionField = MongoDbConnection.class.getDeclaredField("collection");
collectionField.setAccessible(true);
@SuppressWarnings("unchecked")
final MongoCollection<Document> collection = (MongoCollection<Document>) collectionField.get(connection);
return collection.getNamespace();
} catch (final Exception exception) {
throw new RuntimeException(exception);
}
}
}
5 changes: 4 additions & 1 deletion log4j-mongodb/src/test/resources/MongoDbAdditionalFields.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
https://logging.apache.org/xml/ns/log4j-config-3.xsd">
<Appenders>
<NoSql name="MONGO">
<MongoDb connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}/testDb.MongoDbAdditionalFieldsIT"/>
<MongoDb
connection="mongodb://localhost:${sys:log4j.mongo.port:-27017}"
databaseName="testDb"
collectionName="MongoDbAdditionalFieldsIT"/>
<KeyValuePair key="A" value="1"/>
<KeyValuePair key="B" value="2"/>
<KeyValuePair key="env1" value="${env:PATH}"/>
Expand Down
Loading
Loading