添加NuGet程序包- Nlog Nlog.Web.AspNetCore
两个包。
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是当前年-月-日
控制器就直接使用就好了
//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(" -------XXXXXXX()异常:"+EX.ToString()+"------- "); return "value"; } }
用于换行 好看点。
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()异常:阿达四六级拉数据-------
nlog自定义配置参数