ASP.NET Core: Logging to a database with NLog

By FoxLearn 3/8/2020 7:19:52 PM   6.91K
This post shows you How to use NLog database in ASP.NET Core.

NLog is an open source logging platform for various .NET platforms, including .NET standard. NLog makes it easy to write to several targets such as file, database.

NLog database asp.net core

Right-clicking on your project, then select Manage Nuget Packages. Next, Search 'NLog', then install 'NLog.Schema', 'NLog.Config', 'NLog.Web.AspNetCore' to your project.

nlog asp.net core

After you finish installing NLog, you should right-click on NLog.config file, then select Properties.

nlog.config

Set Copy to Output Directory to Copy if newer

NLog.Web.AspNetCore logging to database

Running the sql script below, to create a log table

CREATE TABLE [dbo].[Log] (
	  [Id] [int] IDENTITY(1,1) NOT NULL,
	  [MachineName] [nvarchar](50) NOT NULL,
	  [Logged] [datetime] NOT NULL,
	  [Level] [nvarchar](50) NOT NULL,
	  [Message] [nvarchar](max) NOT NULL,
	  [Logger] [nvarchar](250) NULL,
	  [Callsite] [nvarchar](max) NULL,
	  [Exception] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
      WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

NLog DB Configuration

Opening your appsettings.json file, then add the log connection string as shown below.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  },
  "AllowedHosts": "*",
  "NLogConnection": {
    "DbProvider": "sqlserver",
    "DbHost": ".",
    "Database": "yourdatabase",
    "User": "your sql user",
    "Password": "your sql password"
  }
}

Opening NLog.config file, then modify your configuration as shown below.

<?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"
      throwConfigExceptions="true"
      internalLogLevel="info"
      internalLogFile="c:\temp\internal-nlog.txt">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>
    <target name="database" xsi:type="Database"
            dbProvider="sqlserver"
            dbHost="${configsetting:name=NLogConnection.DbHost}"
            dbDatabase="${configsetting:name=NLogConnection.Database}"
            dbUserName="${configsetting:name=NLogConnection.User}"
            dbPassword="${configsetting:name=NLogConnection.Password}">
      
      <commandText>
        insert into dbo.Log (
        MachineName, Logged, Level, Message,
        Logger, Callsite, Exception
        ) values (
        @MachineName, @Logged, @Level, @Message,
        @Logger, @Callsite, @Exception
        );
      </commandText>
      <parameter name="@MachineName" layout="${machinename}" />
      <parameter name="@Logged" layout="${date}" />
      <parameter name="@Level" layout="${level}" />
      <parameter name="@Message" layout="${message}" />
      <parameter name="@Logger" layout="${logger}" />
      <parameter name="@Callsite" layout="${callsite}" />
      <parameter name="@Exception" layout="${exception:tostring}" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="database" />
  </rules>
</nlog>

Opening your HomeController, then add your logging as show below.

public IActionResult Index()
{
    _logger.LogInformation("nlog database asp.net core");

    return View();
}

To solve NLog.Web.AspNetCore no longer logging to database you should install the System.Data.SqlClient to your project. You can download and install it from Manage Nuget Packages.

Through this post, I showed you how to use NLog and log error to database in ASP.Net Core. Using NLog you can easily integrate logging in ASP.NET Core without writing code.