1. Introduction of NuGet Packages
Nlog
Nlog.Web.AspNetCore
2. Add the Nlog configuration file
1 <?XML version= "1.0" encoding= "Utf-8"?>2 <Nlogxmlns= "Http://www.nlog-project.org/schemas/NLog.xsd"3 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"4 Autoreload= "true"5 Internalloglevel= "Warn"6 Internallogfile= "Internal-nlog.txt">7 <!--define various log targets -8 <Targets>9 <!--write logs to file -Ten <TargetXsi:type= "File"name= "Allfile"FileName= "Nlog-all-${shortdate}.log" One Layout= "${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> A - <TargetXsi:type= "File"name= "Ownfile-web"FileName= "Nlog-my-${shortdate}.log" - Layout= "${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> the <TargetXsi:type= "Null"name= "Blackhole" /> - </Targets> - <rules> - <!--All logs, including from Microsoft - + <Loggername="*"MinLevel= "Trace"WriteTo= "Allfile" /> - + <!--Skip Microsoft Logs and so logs only own logs - A <Loggername= "microsoft.*"MinLevel= "Trace"WriteTo= "Blackhole"Final= "true" /> at <Loggername="*"MinLevel= "Trace"WriteTo= "Ownfile-web" /> - </rules> - </Nlog>
3. Using Nlog
Configuring the configuration log middleware in StartUp.cs
1 Public voidConfigure (Iapplicationbuilder app, ihostingenvironment env,iloggerfactory loggerfactory)2 {3 app. Usestaticfiles ();4//Use Nlog as logging Tool 5 Loggerfactory.addnlog () 6//Introduce Nlog config file 7 env. Configurenlog ("Nlog.config");8 if(env. Isdevelopment ())9 {Ten app. Usedeveloperexceptionpage (); One } A app. Usemvc (); -}
4. Write logs using Nlog in the program
The following is an example injected into the controller
1 Public classValuescontroller:controller2 {3 4 PrivateIlogger<valuescontroller>logger;5 PublicValuescontroller (ilogger<valuescontroller>_logger)6 {7Logger =_logger;8 }9 //GET api/valuesTen [HttpGet] One Public stringGet () A { -Logger. LogError ("123"); - return "value"; the}
Call the API, and then view the file directory
5. Log files generated under the specified directory
People will find that the file is generated in the project directory, log many times, will cause the file directory is too messy
At this point, just change the contents of the Nlog.config as follows to generate in the logs directory
<Targets> <!--write logs to file - <TargetXsi:type= "File"name= "Allfile"FileName= "logs/all/nlog-all-${shortdate}.log"Layout= "${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <TargetXsi:type= "File"name= "Ownfile-web"FileName= "logs/my/nlog-my-${shortdate}.log"Layout= "${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <TargetXsi:type= "Null"name= "Blackhole" /> </Targets>
. NET Core uses nlog logging