ASP.NET Core 添加日誌NLog

來源:互聯網
上載者:User

標籤:set   short   方法   pps   file   tor   views   reload   安裝   

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

 

2.添加日誌設定檔,在項目指定目錄下添加設定檔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">  <!-- 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)

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

4.在startup.cs檔案Configure中添加

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



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

ASP.NET Core 添加日誌NLog

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.