ASP.NET Core 添加日誌NLog

1.在Nuget上搜索 NLog.Extensions.Logging 安裝最新版git

 

2.添加日誌配置文件,在項目指定目錄下添加配置文件nlog.config,內容添加以下:github

<?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">

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <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}" />

   
    <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}" />

    <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>

 

3.將nlog.config添加到project.json配置文件中(若配置文件在指定config目錄下,能夠添加config/*.config)web

  "publishOptions": { "include": [ "wwwroot", "Views", "appsettings.json", "web.config", "nlog.config" ] },

4.在startup.cs文件Configure中添加json

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
env.ConfigureNLog("nlog.config");
…………app



5.記錄日誌方法
(1) public class HomeController : Controller { private static Logger Logger = LogManager.GetCurrentClassLogger(); public IActionResult Index() { Logger.Info("Index page says hello"); return View(); }
…………


(2) public abstract class BaseController<T> : Controller
{
protected ILogger<T> Logger { get; set; }
    public BaseController(ILogger<T> logger, IOptions<ApplicationSiteConfig> appConfig)
{
this.Logger = logger;
}
…………


參考:https://github.com/NLog/NLog.Extensions.Logging
相關文章
相關標籤/搜索