Net core learning tutorial simple use of log component in MVC

Time:2019-12-10

Preface

This article is based on. Net core 2.0, just skimming the water, not in simple terms. Introduced to you about. Net core’s use of log component in MVC, and shared it for your reference and learning. I won’t say much next, let’s take a look at the detailed introduction

Catalog

Using the built-in logging component

Simple transition to third-party components – NLog

Use built-in logs

Next, use the controller homecontroller.cs for demonstration.

Using microsoft.extensions.logging is required;

Scenario 1:


public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILoggerFactory loggerFactory)
  {
   _logger = loggerFactory.CreateLogger(typeof(HomeController));
  }
 }

Option two:


public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILogger<HomeController> logger)
  {
   _logger = logger;
  }
 }

Option three:


public class HomeController : Controller
 {
  private readonly ILogger _logger ;

  public HomeController(ILogger logger)
  {
   _logger = logger;
  }
 }

In the past, we will independently encapsulate different log level methods such as debug, info and error. Now let’s see how the built-in methods are used?

Add index() method in homecontroller for testing.

public IActionResult Index()
  {
   _Logger. Logdebug ($"test: {datetime. Now. ToString (cultureinfo. Invariantculture)}");
   _Logger. Logerror ($"test: {datetime. Now. ToString (cultureinfo. Invariantculture)}");
   _Logger. Loginformation ($"test: {datetime. Now. ToString (cultureinfo. Invariantculture)}");

   return Json(Guid.NewGuid());
  }

In the output results, we can see that different levels of logs will be marked with different colors in the console.

 

There are multiple method overloads for each level of log, such as loginformation (). The code shown in the example uses the simple one, that is, the last one.

//
    // Abstract:
    //   Formats and writes an informational log message.
    //
    // parameter:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  eventId:
    //   The event id associated with the log.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args);
    //
    // Abstract:
    //   Formats and writes an informational log message.
    //
    // parameter:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  exception:
    //   The exception to log.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args);
    //
    // Abstract:
    //   Formats and writes an informational log message.
    //
    // parameter:
    //  logger:
    //   The Microsoft.Extensions.Logging.ILogger to write to.
    //
    //  message:
    //   Format string of the log message.
    //
    //  args:
    //   An object array that contains zero or more objects to format.
    public static void LogInformation(this ILogger logger, string message, params object[] args);

Other details and details, or you can refer to the official document for other log components: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/? Tabs = aspnetcore2x

Simple transition to third-party components – NLog

Nuget installs nlog.web.aspnetcore (the latest nuget is 4.4.1, but the official tutorial is 4.5. Xiaobian uses 4.4.1 for demonstration). For 4.5 +, please refer to official: https://github.com/nlog/nlog.web/wiki/getting-started-with-asp.net-core-2

The following shows how to simply migrate the built-in components to NLog.

First create the configuration file nlog.config in the root directory. Remember to change the attribute to always copy to the directory:


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


 <!-- the targets to write to -->
 <targets>
  <!-- write logs to file -->
  <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
      layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

  <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
  <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
      layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
 </targets>

 <!-- rules to map from logger name to target -->
 <rules>
  <!--All logs, including from Microsoft-->
  <logger name="*" minlevel="Trace" writeTo="allfile" />

  <!--Skip non-critical Microsoft logs and so log only own logs-->
  <logger name="Microsoft.*" maxLevel="Info" final="true" /> <!-- BlackHole without writeTo -->
  <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
 </rules>
</nlog>

Modify the configure () method in the startup. CS class. No other changes are needed.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
      Loggerfactory. Addnlog(); // add NLog 
      Env. Configurenog ("NLog. Config"); // read NLog configuration file 

      //...    
    }

Start the program and you will find:

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.