Skip to content

ASP.NET Core logging to a database with NLog

ASP.NET core has seen rapid development in the last years. Additionally, there were some breaking changes since version 1, for example, the project.json file got removed. Unfortunately, the documentation is lacking behind this rapid development. I had exactly this problem when I wanted to use NLog to log to my database. There was plenty of documentation but none of it worked because it was for .net core 1.x.

Today, I want to talk about how I implemented NLog with ASP.NET core 2.2 and how I configured it to log to my database. You can find the source code for the following demo onĀ GitHub.

Installing Nlog

I created a new web project with .net core and the MVC template and added the NLog.Web.AspNetCore NuGet package. Next, I create a new file NLog.config in the root folder of my solution. This file will contain all the configs for NLog. Now it is time to fill the config file with some content. You can find the source code for this demo on Github.

Implementing the Nlog config

To get started, create a database and then the Log table. You can find the script to create the table at the bottom of my config file. Now let’s inspect the config file:

NLog internal logging
NLog internal logging

The first section of the file is for internal logs of Nlog. These logs come in handy when you have a problem with Nlog. There you can configure what level of logging you want and where the log file should be created. You can also configure whether the file should be reloaded on save with autoReload.

Configure the database connection
Configure the database connection

The next section is for configuring the database connection. The variables are read from the appsettings.json from the NlogConnection section. You can see the appsettings.json section on the following screenshot.

Settings for Nlog from appsettings.json
Settings for Nlog from appsettings.json

The commandText section defines the insert statement. This is straight forward and you don’t have to edit anything.

Setting up the insert statement for logging
Setting up the insert statement for logging

The last section lets you specify rules about your log. You can configure which logger should log where. In my example, every logger logs messages with the log level Info and higher into the database. Another example could be to log information from one logger to the database and the information from another one to a file.

Rules for logging
Rules for logging

Using Nlog

Using Nlog in your application is really simple. First, you have to tell your WebHost to use Nlog in the CreateWebHostBuilder by simply adding .UseNlog() at the end of the statement.

Use Nlog in the WebHostBuilder
Use Nlog in the WebHostBuilder

That’s all you have to do. Now you can already use the logger in your application. To use the logger, inject the ILogger interface with the type of the class which uses it. The ILogger interface provides useful methods like LogInformation() or LogCritical(). Call one of the methods and insert your log message.

Use ILogger to log messages
Use ILogger to log messages

Testing the implementation

To test that the logging is working, you have only to start your application and call one of the controllers which do some logging. Then you can check in your database in the Log table and you should see the log entries there.

On the following screenshot, you can see that I called the Index and the Privacy method once which create a log entry for both calls.

Log entries in the Log table
Log entries in the Log table

Conclusion

This post showed how simple it is to set up and use NLog with your ASP.NET MVC Core application. All you have to do is installing the NuGet, adding the nlog.config file and use it in your application.

You can find more information about NLog on their website and you can find the source code of today’s demo on Github.

Published inASP.NET MVC / Core

10 Comments

  1. No pictures No pictures

    Why are all the code in pictures?!?!

    • There is a problem with the layout when I paste code. I have to admit that I haven’t invested much time into that.

      You can always get the whole code from Github though.

  2. Cleo Cleo

    Hi, I’m trying to follow your example. But I’m using integrated security instead of username and password, how should I modify the target configuration to make it work?

    Thanks in advance.

    • Hi Cleo,

      the following config should work (haven’t tested it though) with integrated security:

      <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd&#x22;
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&#x22;
      autoReload="true"
      internalLogLevel="info"
      internalLogFile="C:\temp\internal-nlog.txt">
      <targets>
      <target
      xsi:type="Database"
      name="database">
      <commandText>INSERT INTO MapApplication.dbo.LogEntries(TimeStamp, Message, Level, Logger) VALUES(GETDATE(), @message, @level, @logger)</commandText>
      <parameter name="@message" layout="${message}" />
      <parameter name="@level" layout="${level}" />
      <parameter name="@logger" layout="${logger}" />
      <!–<dbProvider>System.Data.SqlClient</dbProvider>–>
      <connectionString>Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True</connectionString>
      </target>
      </targets>
      <rules>
      <logger name="*" minlevel="Error" writeTo="database" />
      </rules>
      </nlog>

  3. Michele Michele

    Your example uses a mvc project. Mine is a wpf application with a xaml class, with database class. Do I proceed with those classes in the same way that you did with the mvc class?

    • Hi Michele,

      I don’t have much experience with WPF but if it is a .net core application, the steps are almost the same except that you would register the logging probably in your OnStartup method.

      Using the Nlog in your classes should be the same since it gets passed into your class via dependency injection.

  4. Alta Sneed Wilmer Easley

    This is really interesting, You are a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I have shared your site in my social networks!

  5. Vishvam Mistry Vishvam Mistry

    Hello, I need to use NLog for logging in db in ASP.Net Core 3.1. Do you have any references regarding it or can you guide me about the changes required?

    • Hi Vishvam Mistry,

      I tried to update the project to .NET Core 3.1 and Nlog to the newest version but I couldn’t get it working. I tried for around half an hour but I don’t get any errors and couldn’t find anything in the official documentation. Unfortunately, I couldn’t even get their sample app running.
      Due to the bad documentation, I would recommend you to look for a different logging framework. I worked in the past (a couple years ago already) with log4net which was easy to set up with a way better documentation.

      • I am working on logging in one of my projects right now and I saw that log4net is not really updated anymore. Instead I am using Serilog (https://serilog.net) now. It has a good documentation and tons of appenders.

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
Follow by Email
LinkedIn
Share