ASP.NET Nlog上手练习小例子

 

 

添加NuGet程序包-             Nlog             Nlog.Web.AspNetCore

两个包。

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            //使用NLog作为日志记录工具
            loggerFactory.AddNLog();
            //引入Nlog配置文件
            env.ConfigureNLog("Nlog.config");
        }
Nlog.config 配置文件
"1.0" encoding="utf-8" ?>
"http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     autoReload="true"
       internalLogLevel="Warn">
  
  
    
    "File" name="file" fileName="/Nlog/log/${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    "File" name="ownFile-web" fileName="/Nlog/log/${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    "Null" name="blackhole" />
  
  
    
    "*" minlevel="Trace" writeTo="allfile" />

    
    "Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    "*" minlevel="Trace" writeTo="ownFile-web" />
  
 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 ActionResultstring>> 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()异常:阿达四六级拉数据-------

 

你可能感兴趣的:(ASP.NET Nlog上手练习小例子)