.Net Core uses NLog to record log to file and database operation method


NLog logging is officially recommended by Microsoft.

Next, by configuring logging to file and Sql Server database.

Step 1: First add the package NLog.Config (which can be added through the Microsoft add package command Install-Package package name, or through the management NuGet package). After the addition is successful, the NLog.config configuration file will be generated. and configure the configuration file. For detailed configuration, please refer to the NLog description on Git.

Here is my personal configuration.

<?xml version="1.0" encoding="utf-8" ?>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
        xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
   <!-- optional, add some variables
   <variable name="myvar" value="myvalue"/>
   See https://github.com/nlog/nlog/wiki/Configuration-file
   for information on customizing logging rules and outputs.
     add your targets here
     See https://github.com/nlog/NLog/wiki/Targets for possible targets.
     See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
     Write events to a file with the date in the filename.
     <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
             layout="${longdate} ${uppercase:${level}} ${message}" />
     <!-- write logs to file -->
     <target xsi:type="File" name="allfile" fileName="Logs/${date:format=yyyyMM}/nlog-all-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" />
     <target xsi:type="File" name="ownFile-web" fileName="Logs/${date:format=yyyyMM}/nlog-own-${shortdate}.log"
              layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
     <target xsi:type="Null" name="blackhole" />
     <target xsi:type="Database" name="database">
         insert into syslogs (Application,Levels,Operatingtime,Operatingaddress,Userid,Logger,Callsite,Requesturl,Referrerurl,Action,Message,Exception)
         values (@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callSite,@requesturl,@referrerurl,@action,@message,@exception);
       <parameter name="@application" layout="WebApi" />
       <parameter name="@levels" layout="${level}" />
       <parameter name="@operatingTime" layout="${date}" />
       <parameter name="@operatingaddress" layout="${aspnet-Request-IP}" />
       <parameter name="@userid" layout="1" />
       <parameter name="@logger" layout="${logger}" />
       <parameter name="@callSite" layout="${callsite}" />
       <parameter name="@requesturl" layout="${aspnet-request-url}" />
       <parameter name="@referrerurl" layout="${aspnet-request}" />
       <parameter name="@action" layout="${aspnet-mvc-action}" />
       <parameter name="@message" layout="${message}" />
       <parameter name="@exception" layout="${exception:tostring}" />
     <!-- add your logging rules here -->
     Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
     <logger name="*" minlevel="Debug" writeTo="f" />
     <!--All logs, including from Microsoft-->
     <!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
     <logger name="*" minlevel="Error" writeTo="allfile" />
     <!--Skip Microsoft logs and so log only own logs-->
     <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
     <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
     <logger name="*" minlevel="Trace" writeTo="database" />    
 <PackageReference Include="NLog.Extensions.Logging" Version="1.2.1" />
 <PackageReference Include="NLog.Web.AspNetCore" Version="4.6.0" />-->

Note: One of the nodes in targets is Database, which is configured to write logs into the database. Note that the log table needs to be added to the database.

  "ConnectionStrings": {
    "DefaultConnection": "Data Source=;Initial Catalog=Test;User ID=sa;Password=123456;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false;"
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
  "AllowedHosts": "*"

Step 2: Add the package NLog.Web.AspNetCore, add &quot;.UseNLog()&quot; to the WebHost in Program.cs (this belongs to the assembly NLog.Web, you need to add the reference using NLog.Web;), that is, add nlog.

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;

namespace WebApi
    public class Program
        public static void Main(string[] args)

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                .UseNLog(); //Add nlog log

Step 3: Add the logging code to the Configure method in Startup.cs, that is, the configuration file that needs to be loaded and the configuration log written to the database connection string code. Note: To avoid the problem of Chinese garbled characters, you need to add the System.Text.Encoding.CodePages package.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
              #region NlogLogging
              // log to database config/NLog.config
              NLog.LogManager.LoadConfiguration(&quot;nlog.config&quot;).GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables[&quot;connectionString&quot;] = Configuration.GetConnectionString(&quot;DefaultConnection&quot;); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Avoid garbled Chinese output in logs
             if (env.IsDevelopment())

Step 4: Use the Microsoft-recommended method to inject the log object in the constructor.

public class UsersController : Controller
        /// <summary>
        /// log object
        /// </summary>
        private readonly ILogger logger;    
         public UsersController(ILoggerFactory loggerFactory)
            this.logger = loggerFactory.CreateLogger<UsersController>();

            #region test log
            logger.LogTrace(&quot;Debug during development, may contain sensitive program data&quot;, 1);
            logger.LogDebug(&quot;It is useful in the short term during the development phase and is beneficial for debugging.&quot;);
            logger.LogInformation(&quot;You visited the home page. The general flow of the tracking program.&quot;);
            logger.LogWarning(&quot;Warning message! Due to program failure or other process exceptions or unexpected events that will not cause the program to stop.&quot;);
            logger.LogError(&quot;Error message. Stopped working due to some failure&quot;);
            logger.LogCritical(&quot;Program or system crashed and encountered catastrophic failure!!!&quot;);

All work done, run the program. Generate log files in the configured NLog path, and at the same time, generate logs in the database.

So far, this article about .Net Core using NLog to record logs to files and databases is introduced. For more information about .Net Core logging to files and databases, please search for previous articles by developpaer or continue to browse the related articles below. I hope you will support developpaer more in the future!