Description
When using log4j-mongodb3 appender with a connection factory , receiving exception
2019-01-20 21:33:02,438 main ERROR Unable to write to database [noSqlManager{ description=databaseAppender, bufferSize=0, provider=mongoDb
{ database=logger } }] for appender [databaseAppender]. org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.apache.logging.log4j.Level.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:184)
at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:199)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:141)
at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
at com.mongodb.operation.BulkWriteBatch$WriteRequestEncoder.encode(BulkWriteBatch.java:387)
Here is my log4j2.xml for the nosql appender
<NoSql name="databaseAppender">
<MongoDb3 databaseName="logger" collectionName="applicationLog" factoryClassName="logger.ConnectionFactory"
factoryMethodName="getNewMongoClient" />
</NoSql>
Here is my ConnectionFactory
public class ConnectionFactory {
public static MongoClient getNewMongoClient ()
{ MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/logger"); MongoClient client = new MongoClient(uri); return client; }}
Work around solution was to add on the Connection Factory my own MongoClient Options, to add the Logger Codec
public static MongoClient getNewMongoClient ()
{ MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder() .codecRegistry(CodecRegistries.fromRegistries( CodecRegistries.fromCodecs(new LevelCodec()), MongoClient.getDefaultCodecRegistry())); MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/logger",optionsBuilder); MongoClient client = new MongoClient(uri); return client; }
I feel this should be added as part of the MongoDbProvider .java, when using a Connection Factory to also set the Codec.