Logging in asp.net core development tutorial using NLog to write log files



This article mainly introduces asp.net core development logging using NLog to write log files, and shares it for your reference and study. I won’t say much next, let’s take a look at the detailed introduction

NLog can be applied to. Net core and asp.net core.

Asp.net core has built-in log support, which can be easily output to the console.

Learn the related use of logging component, and use NLog to write logs to file records.

Logging usage

Create a new asp.net core project. For convenience, I choose a web application and change the authentication to no authentication.

After the creation, the corresponding class library will be referenced automatically. So we can use the logger directly.

Use of logger in controller

public class HomeController : Controller
  private readonly ILogger<HomeController> _logger;

  public HomeController(ILogger<HomeController> logger)
   _logger = logger;
  public IActionResult Index()
   _Logger.loginformation ("you visited the home page");
   _Logger.logwarning ("warning messages");
   _Logger.logerror ("error message");
   return View();

  public IActionResult About()
   ViewData["Message"] = "Your application description page.";

   return View();

  public IActionResult Contact()
   ViewData["Message"] = "Your contact page.";

   return View();

  public IActionResult Error()
   return View();

Objects can be used directly with di.

You will find that the output of log information is garbled. Here we need to specify the output format.

Need to addSystem.Text.Encoding.CodePagesQuote

Install-Package System.Text.Encoding.CodePages -Pre

Then in startup.cs – > configure

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

In this way, there will be no garbled code in the console display.

Log level: trace – debug – Information – warning – error – critical

Levels range from large to small. For example, trace contains all the information.

NLog use

The use of NLog in asp.net core.

1. Add reference.

Install-Package NLog.Extensions.Logging -Pre

2. Add nlog.config file in the project.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"

 <!-- define various log targets -->
 <!-- write logs to file -->
 <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
     layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

 <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
    layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" />

 <target xsi:type="Null" name="blackhole" />

 <!--All logs, including from Microsoft-->
 <logger name="*" minlevel="Trace" 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" />

3. In startup.cs – “configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
   Loggerfactory. Addnlog(); // add NLog

Run the program, you will find that there are two more documents under the project to prove the successful implementation.

Herenlog-all-*.log Is to record all the logs,nlog-own-*.logRecord the information about skipping the class library output at the beginning of Microsoft, and the rest.

4. Precautions for dotnet publish

Add nlog.config to the publishoptions node of project.json

"publishOptions": {
 "include": [
  "NLog. Config" // add NLog configuration file

GitHub :https://github.com/linezero/Blog/tree/master/NETCoreLogging


The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.