在asp.net core中使用NLog,亲测原创 放心使用

第一步:nuget  引入  NLog.Web.AspNetCore 4.5+

 

第二步:放入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"
      internalLogFile="c:\temp\internal-nlog.txt">

  <!-- 加载ASP.NET Core插件 -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- 输出目的地 -->
  <targets>
    <!-- 输出到文件,这个文件记录所有日志 -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <!-- 另外一个日志记录文件,户口也跳过Microsoft开头相关日志信息 -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <!-- write to the void aka just remove -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- 写入目的地的规则 -->
  <rules>
    <!--全部记录,包括Microsoft开头的相关日志信息-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--跳过Microsoft开头的相关日志信息-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

第三步:写代码

 NLog.Logger logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        public IActionResult Index()
        {            
            logger.Info("普通信息日志-----------");
            logger.Debug("调试日志-----------");
            //Logger.Error("错误日志-----------");
            //Logger.Fatal("异常日志-----------");
            //Logger.Warn("警告日志-----------");
            //Logger.Trace("跟踪日志-----------");
            //Logger.Log(NLog.LogLevel.Warn, "Log日志------------------");
            return View();
        }

第四步:查看日志

根据nlog配置的地址查看,很重要,我放在c盘了

总结:就是这么简单,轻松愉快的搞定,祝家族的程序猿(程序媛)们开心快乐!!!

附件:百度网盘-链接:https://pan.baidu.com/s/18ijC21h8vwRDpslsXx3hrg 密码:73jo

猜你喜欢

转载自blog.csdn.net/qqqqqqqqqq198968/article/details/81458657
今日推荐