[. Net Core] using the log component in Mvc, coremvc

Source: Internet
Author: User

[. Net Core] using the log component in Mvc, coremvc
Simple use of log components in Mvc

Based on. Net Core 2.0, this article is just a bit of water, not a simple introduction.

 

Directory
  • Use built-in log Components
  • Simple transition to a third-party component-NLog

 

Use built-in logs

First, using Microsoft. Extensions. Logging;

The following uses the Controller HomeController. cs for demonstration.

 

Solution 1:

    public class HomeController : Controller    {        private readonly ILogger _logger ;        public HomeController(ILoggerFactory loggerFactory)        {            _logger = loggerFactory.CreateLogger(typeof(HomeController));        }    }

 

Solution 2:

    public class HomeController : Controller    {        private readonly ILogger _logger ;        public HomeController(ILogger<HomeController> logger)        {            _logger = logger;        }    }

 

Solution 3:

    public class HomeController : Controller    {        private readonly ILogger _logger ;        public HomeController(ILogger logger)        {            _logger = logger;        }    }

 

All three methods are used to obtain logging recorder objects through injection. In the past, we independently encapsulated methods of different levels, such as Debug, Info, and Error, now let's see how the built-in method is used?

 

Add the Index () method to 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 result, we can see that different log levels are marked in different colors on the console.

//// Summary: // Formats and writes an informational log message. //// parameter: // logger: // The Microsoft. extensions. logging. ILogger to write. /// 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. /// 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. /// 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 want to use other log components can refer to the official documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging? Tabs = aspnetcore2x

 

Simple transition to a third-party component-NLog

Nuget install NLog. Web. AspNetCore (currently the latest Nuget version is 4.4.1, but the official tutorial is 4.5, which is used for demonstration in small series 4.4.1 ). If you need 4.5 + can refer to the official: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

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.

Public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory. addNLog (); // Add NLog env. enlog ("nlog. config "); // read the Nlog configuration file //...}

 

Start the program and you will find:

 

 

 

Http://www.cnblogs.com/liqingwen/p/8613538.html.

Related Articles:

[. Net Core] simple reading of json configuration files

[. Net Core] simple use of built-in Mvc Ioc

[. Net Core] simple use of built-in Mvc Ioc (continued)

[. Net Core] simple use of log components in Mvc

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.