ASP. NET Core learn the third NLog log, corenlog

Source: Internet
Author: User
Tags webhost

ASP. NET Core learn the third NLog log, corenlog

The previous article briefly introduced how to use logs. It is only used for learning, not to mention that logs can only be output on the console.

NLog is already a member of the logstore and is easy to use. The environment described in this article is in. net core 2.0, and the current version is only beta.

1. installation and configuration 1. Installation

The command is as follows:

PM> Install-Package NLog.Web.AspNetCore -Version 4.5.0-beta04
2. Create a configuration file

Under the root directory of the web project, create the configuration file nlog. config and set the "Copy to output directory" attribute of the file to "always copy ".
Example:

<?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}" />    <!-- 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}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />    <!-- write to the void aka just remove -->    <target xsi:type="Null" name="blackhole" />  </targets>  <!-- rules to map from logger name to target -->  <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. Initialization

Update program. cs and add reference

using NLog.Web;

Modify code

public static void Main(string[] args){    // NLog: setup the logger first to catch all errors    var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();    try    {        logger.Debug("init main");        BuildWebHost(args).Run();    }    catch (Exception e)    {        //NLog: catch setup errors        logger.Error(e, "Stopped program because of exception");        throw;    }}public static IWebHost BuildWebHost(string[] args) =>    WebHost.CreateDefaultBuilder(args)        .UseStartup<Startup>()        .UseNLog() // NLog: setup NLog for Dependency injection        .Build();
Ii. Use

After configuration, inject ILogger into the Controller to write logs.

public class HomeController : Controller{    private readonly ILogger<HomeController> _logger;    public HomeController(ILogger<HomeController> logger)    {        _logger = logger;    }    public IActionResult Index()    {        _logger.LogInformation("Index page says hello");        return View();    }}
Iii. log output

Access the index to view the two generated files in the log directory.

Nlog-all-2017-11-18.log

2017-11-18 23:09:02.2839||DEBUG|Tkx.Web.Program|init main 2017-11-18 23:09:02.6079||INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using 'C:\Users\Administrator\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest. 2017-11-18 23:09:03.0070||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 POST http://localhost:59491/account/login application/x-www-form-urlencoded 26 2017-11-18 23:09:03.0320||INFO|Microsoft.AspNetCore.Cors.Infrastructure.CorsService|Policy execution successful. 2017-11-18 23:09:03.1720||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method Tkx.Web.Controllers.AccountController.Login (Tkx.Web) with arguments (Tkx.WebApi.Models.User.UserLogin) - ModelState is Valid 2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================ 2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123 2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================ 2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123 2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1 2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService: 2017-11-18 23:09:03.3500||INFO|Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor|Executing JsonResult, writing value Tkx.Web.ResponseMessage. 2017-11-18 23:09:03.5290||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action Tkx.Web.Controllers.AccountController.Login (Tkx.Web) in 398.631ms 2017-11-18 23:09:03.5440||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request finished in 543.2871ms 200 application/json; charset=utf-8

Nlog-own-2017-11-18.log

2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login2017-11-18 23:09:03.1760||INFO|Tkx.Web.Controllers.AccountController|LOGIN IS START:admin 123 |url: http://localhost/account/login|action: login2017-11-18 23:09:03.1950||INFO|Tkx.Web.Controllers.AccountController|================ |url: http://localhost/account/login|action: login2017-11-18 23:09:03.1950||INFO|Tkx.IBusiness.Implement.UserService|UserService param:admin 123 |url: http://localhost/account/login|action: login2017-11-18 23:09:03.3440||INFO|Tkx.IBusiness.Implement.UserService|UserService count:1 |url: http://localhost/account/login|action: login2017-11-18 23:09:03.3500||INFO|Tkx.IBusiness.Implement.UserService|UserService: |url: http://localhost/account/login|action: login

It is as easy to use at the business layer, as long as the library is introduced at the business layer. The UserService shown in the log is my business layer.

Related Documents

Project address: https://github.com/NLog/NLog.Web nlog usage
Https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
Detailed instructions for using the configuration file
Https://github.com/NLog/NLog/wiki/Configuration-file

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.