天天看点

.NET Core2.0 NLog使用实例

  一:使用Nuget执行命令下载NLog相关依赖

          Install-Package NLog.Extensions.Logging -Pre

           Install-Package NLog.Web.AspNetCore

  二:创建好Nlog配置文件

   在项目目录中新建一个xml文件nlog.config       

.NET Core2.0 NLog使用实例
<?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="internal-nlog.txt">

  <!--define various log targets-->
  <targets>

    <!--write logs to file-->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${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>
           

  三.Startup.cs中添加使用的服务

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

            loggerFactory.AddNLog();//添加NLog
            env.ConfigureNLog("nlog.config");//读取Nlog配置文件
 
            //.............
        }
           

 四:使用日志

static Logger Logger = LogManager.GetCurrentClassLogger();


        public IActionResult Index()
        {
            Logger.Info("普通信息日志-----------");
            Logger.Debug("调试日志-----------");
            Logger.Error("错误日志-----------");
            Logger.Fatal("异常日志-----------");
            Logger.Warn("警告日志-----------");
            Logger.Trace("跟踪日志-----------");
            Logger.Log(NLog.LogLevel.Warn, "Log日志------------------");

            return View();
        }
           

 五:日志的位置默认是在bin\Debug\netcoreapp2.0下面

.NET Core2.0 NLog使用实例

走在巨人的肩膀上,没有理由不上进,希望大牛都多指点

——————————————————————————————————————————————————————

继续阅读