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

Time:2019-11-24

Preface

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)
  {
   Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

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"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  autoReload="true"
  internalLogLevel="Warn"
  internalLogFile="internal-nlog.txt">

 <!-- define various log targets -->
 <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" />
 </targets>

 <rules>
 <!--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" />
 </rules>
</nlog>

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": [
  "wwwroot",
  "Views",
  "appsettings.json",
  "web.config",
  "NLog. Config" // add NLog configuration file
 ]
 },

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

summary

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.

Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]