ASP. NET Core 2.1:12. Built-in logs, using Nlog to output logs to a file

Source: Internet
Author: User

Applications can not be separated from the log, although the use of VS has a powerful debugging capabilities, the development process is not too complicated to output the log (think of print and echo of the wood), but in some complex process and the application of daily running log is still very useful.

ASP. NET core provides a built-in log, but does not understand that it is output to a file, only in the output of VS, who knows how to tell me. (ASP. NET Core Series Catalog ) This example GitHub

First, the use of built-in logs

Previous: How to run a task in the background using the built-in log, directly in the construction of the injection, and then directly use, very convenient

         Public Tokenrefreshservice (ilogger<tokenrefreshservice> logger)        {            = logger;        }         protected Override Async Task Executeasync (cancellationtoken stoppingtoken)        {            _logger. Loginformation ("Service starting");            // ************        }

You can then see the output log in the Output window:

Want to output it to txt, do not find the corresponding method, try the common Nlog bar

Second, use Nlog to output the log to file a. Install Nlog

Search and install NLog.Web.AspNetCore in NuGet, the current version is 4.5.4

B. Adding a configuration file

Create a new file Nlog.config, right-click its properties, and set its copy to output directory to always copy. The file contents are as follows

<?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"throwconfigexceptions="true"Internalloglevel="Info"Internallogfile="D:\log\internal-nlog.txt"> <!--the targets to write and <targets> <!--write logs to file-to-<target Xsi:type ="File"Name="Allfile"Filename="D:\log\nlog-all-${shortdate}.log"Layout="${longdate}|${event-properties:item=eventid_id:whenempty=0}|${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="D:\log\nlog-own-${shortdate}.log"Layout="${longdate}|${event-properties:item=eventid_id:whenempty=0}|${uppercase:${level}}|${logger}|${message} ${ Exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}"/> </targets> <!--rules to map fromLogger name to target-<rules> <!--all logs, including fromMicrosoft--> <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-<logger name="*"Minlevel="Trace"writeto="Ownfile-web"/> </rules></nlog>
C. Modify the Program.cs file

In the . add a sentence after usestartup<startup> () . Usenlog ()

Third, the matters needing attention

As described in section II, Nlog is ready to use, with some details to give a brief explanation:

1. The name of the file nlog.config should be the default read file name, if you use a different name, you can set the Configurenlog method in the Program.cs file, see the following code example.

2. Now, as in the example in the first section, the output box of VS is still in the input log, that is, both are in effect, and want to use only Nlog, you can call logging. Clearproviders ();

code example:

1      Public class Program2     {3          Public Static voidMain (string[] args)4         {5NLog.Web.NLogBuilder.ConfigureNLog ("Nlog1.config");//If you don't use the default name, write a 1 more6 Createwebhostbuilder (args). Build (). Run ();7         }8 9          Public StaticIwebhostbuilder Createwebhostbuilder (string[] args) =Ten Webhost.createdefaultbuilder (args) One. Usestartup<startup>() A. Configurelogging (logging = -                 { -Logging. Clearproviders ();//removing other log handlers that have already been registered theLogging. Setminimumlevel (Microsoft.Extensions.Logging.LogLevel.Trace);//set the minimum log level -                 }) -                 .  Usenlog ();  -}

Iv. Brief description of Nlog configuration

"Brief" about the configuration of Nlog:

1. The above mentioned a log level, which is roughly divided into 6, from low to high as follows:

1 logger. Logtrace (); 2 logger. Logdebug (); 3 logger. Loginformation (); 4 logger. Logwarning (); 5 logger. LogError (); 6 Logger. Logcritical ();

2. Through the above example, see the output of the log file has 3, which is configured in the Nlog.config, through the file name can find the corresponding configuration.

    • The Internal-nlog records the Nlog startup and load config information.
    • Nlog-all records all logs.
    • Nlog-own recorded our custom logs.

What is this for? Config has two key tags <targets> and <rules>

  • <targets> is used to configure output-related content, such as the type attribute can be selected as file, Mail, console, etc., for setting the output target, the Layout property is used to set the output information of the constituent elements and format.
  • <rules>: Here is a hole , a look at this label, simple to understand the "rules", and just the example of the two <rule> exactly corresponds to the above two <target>,writeto properties specify the corresponding <target>. Can look carefully, two of the <rule> configuration is similar, why the following one only output our custom log? See Help to know this is a " routing table ", and the logs are matched from top to bottom. <logger name="microsoft.*" maxlevel="Info" final= " true "/> " final="true" filters out "microsoft.*" the log.

ASP. NET Core 2.1:12. Built-in logs, using Nlog to output logs to a file

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.