添加NuGet程序包- Nlog Nlog.Web.AspNetCoreweb
兩個包。api
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //使用NLog做爲日誌記錄工具 loggerFactory.AddNLog(); //引入Nlog配置文件 env.ConfigureNLog("Nlog.config"); }
Nlog.config 配置文件
<?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="Warn"> <!--define various log targets--> <targets> <!--write logs to file--> <target xsi:type="File" name="file" fileName="/Nlog/log/${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="/Nlog/log/${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <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>
fileName="/Nlog/log/${shortdate}.log" 會在你的項目所在盤目錄下建一個Nlog文件夾/log文件夾-裏面就是日誌文件txt了。 shortdate是當前年-月-日
控制器就直接使用就行了app
//Route加了這個連接就是 api/values/5 ----沒加 values/5 [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } Logger logger = LogManager.GetCurrentClassLogger(); // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { Exception EX = new Exception(); logger.Error("\r\n-------XXXXXXX()異常:"+EX.ToString()+"-------\r\n"); return "value"; } }
\r\n 用於換行 好看點。
2019-09-27 17:18:06.5617|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據------- 2019-09-27 17:18:30.9757|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據------- 2019-09-27 17:18:31.2428|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據------- 2019-09-27 17:18:31.3779|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據------- 2019-09-27 17:18:31.5394|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據------- 2019-09-27 17:18:31.6806|Nlog_test.Controllers.ValuesController|ERROR| -------XXXXXXX()異常:阿達四六級拉數據-------