NLog and MongoDB

NLog is one of the most commonly used free logging platform, thanks to its flexibility and rich capabilities. Most often than not, our application requires logs that could be written out to raw files. But NLog provides the ability to do more, including writing to databases like MongoDb. In this blog post, we will address how to write NLog messages to MongoDB.

For the sake of example in this post, we will use Docker containers to set up our Database and application (a Web API).

MongoDb and MongoExpress

Let us first make sure we have MongoDb container running. We will also have a container running the MongoExpress for us to view and manage the MongoDb instance.

We can begin by creating a Docker-Compose file that looks like the following.

version: '3.4'

services:

  authServiceLog:
    image: mongo:latest
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: ********
    networks:
        mongo_network:

    volumes:
        - authServiceLog_Data:/data/db 


  mongo-express:
    image: mongo-express
    restart: always
    ports:
        - 8081:8081
    environment:
        ME_CONFIG_MONGODB_ADMINUSERNAME: root
        ME_CONFIG_MONGODB_ADMINPASSWORD: ********
        ME_CONFIG_MONGODB_URL: mongodb://root:********@authServiceLog:27017/
    networks:
        mongo_network:

volumes:
    authServiceLog_Data:
        name: "vol_nt_auth_log_mongo"

networks:
    mongo_network:
        driver: bridge 
  

We now have our MongoDb and MongoExpress running. The next step is to configure NLog to write to the database

Configure NLog

The first step would be install the required nuget packages in our Web API. Ensure that the following packages are installed.

NLog
NLog.Extensions.Loggging
NLog.Web.AspNetCore
NLog.Mongo

With the required libararies in place, we will proceed to configure NLog. NLog configuration is done using NLog.config file. Our example NLog.config looks like the following.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      >

	<!-- enable asp.net core layout renderers -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
		<add assembly="NLog.Mongo"/>
	</extensions>

	<!-- the targets to write to -->
	<targets>
		<target xsi:type="Mongo"
          name="mongolog"
          connectionString="mongodb://root:admin123@authServiceLog:27017"
          collectionName="logs"
          databaseName="ntauthlog"
		  cappedCollectionSize="26214400"
          includeDefaults="false">

			<field name="Date" layout="${date}" bsonType="DateTime" />
			<field name="Level" layout="${level}"/>
			<field name="Message" layout="${message}" />
		</target>

	</targets>

	<!-- rules to map from logger name to target -->
	<rules>
		<logger name="*" minlevel="info" writeTo="mongolog" />
	</rules>
</nlog>

The final step is to ensure that the NLog Logging is added to our middleware list. This could be done using the following code.

builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();

That’s all we need to do. Now we have successfully configured the NLog to write to MongoDb.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s