[. Net Core] Simple use of the log component in MVC

Source: Internet
Author: User

Simple use of the log component in MVC

Based on. Net Core 2.0, this article is just Dragonfly water, not in the most understandable.

Directory
    • Using the built-in log components
    • Simple transition to third-party components-NLog

Using built-in logs

The following is a demonstration using the controller HomeController.cs.

A using Microsoft.Extensions.Logging is required;

Programme one:

     Public class Homecontroller:controller    {        privatereadonly  ILogger _logger;          Public HomeController (iloggerfactory loggerfactory)        {            = Loggerfactory.createlogger (typeof(HomeController));        }    }

Scenario Two:

     Public class Homecontroller:controller    {        privatereadonly  ILogger _logger;          Public HomeController (ilogger logger)        {            = logger;        }    }

Programme III:

     Public class Homecontroller:controller    {        privatereadonly  ILogger _logger;          Public HomeController (ILogger logger)        {            = logger;        }    }

Three are all injected to get the logger object, in the past, we will individually encapsulate the different log levels like these Debug, Info and Error methods, and now we look at how the built-in method is used?

Test by adding the Index () method within the HomeController.

         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 we can see that different log levels are labeled in different colors in the console.

There are several method overloads for each level of Log, such as Loginformation (), which is used in the code shown in the example, which is the last one.

        //        //Summary://Formats and writes an informational log message. //        //Parameters://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 voidLoginformation ( ThisILogger logger, EventId EventId,stringMessageparams Object[] args); //        //Summary://Formats and writes an informational log message. //        //Parameters://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 voidLoginformation ( ThisILogger logger, Exception Exception,stringMessageparams Object[] args); //        //Summary://Formats and writes an informational log message. //        //Parameters://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 voidLoginformation ( ThisILogger Logger,stringMessageparams Object[] args);

  

Other details and details, or if you wish to use other log components, refer to the official documentation: HTTPS://DOCS.MICROSOFT.COM/EN-US/ASPNET/CORE/FUNDAMENTALS/LOGGING/?TABS=ASPNETCORE2X

Simple transition to third-party components-NLog

NuGet installs NLog.Web.AspNetCore (currently NuGet is up to 4.4.1, but the official tutorial is 4.5, and the mini-series uses 4.4.1 to demonstrate). If you need 4.5 + can refer to the official: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

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

Create the configuration file Nlog.config in the root directory, and Remember to modify the properties to always copy to the directory :

<?XML version= "1.0" encoding= "Utf-8"?><Nlogxmlns= "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 -    <TargetXsi: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 -    <TargetXsi: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 -    <Loggername="*"MinLevel= "Trace"WriteTo= "Allfile" />    <!--Skip non-critical Microsoft logs and so log only own logs -    <Loggername= "microsoft.*"Maxlevel= "Info"Final= "true" /> <!--blackhole without WriteTo -    <Loggername="*"MinLevel= "Trace"WriteTo= "Ownfile-web" />  </rules></Nlog>

Modify the Configure () method in the Startup.cs class, and there is no need to make any changes elsewhere.

         Public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory)        {            loggerfactory.addnlog ();     // add Nlog              Env. Configurenlog ("nlog.config");    // Read the Nlog configuration              file // ...                }

Start the program and you will find:

"Original" http://www.cnblogs.com/liqingwen/p/8613538.html

Related articles:

"[. Net Core] Simple Read JSON configuration file"

[. Net Core] Simple to use MVC built-in Ioc "

[. Net Core] Simple to use MVC built-in IOC (cont.)

[. Net Core] Simple use of the log component in MVC

[. Net Core] Simple use of the log component in MVC

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.