ASP.NET Core 開發-Logging 使用NLog 寫記錄檔

來源:互聯網
上載者:User

標籤:ica   har   錯誤   builder   cep   png   警告   驗證   gis   

ASP.NET Core 開發-Logging 使用NLog 寫記錄檔。

NLog 可以適用於 .NET Core 和 ASP.NET Core 。

ASP.NET Core已經內建了日誌支援,可以輕鬆輸出到控制台。

學習Logging 組件的相關使用,使用NLog 將日誌寫入到檔案記錄。

 

Logging 使用

建立一個 ASP.NET Core 項目,為了方便,我選擇Web 應用程式,改身分識別驗證 改為 不進行身分識別驗證。

 

建立好以後,會自動引用好對應的 類庫。這樣我們就可以直接使用 Logger。

Logger 在 Controller的使用

    public class HomeController : Controller    {        private readonly ILogger<HomeController> _logger;        public HomeController(ILogger<HomeController> logger)        {            _logger = logger;        }        public IActionResult Index()        {            _logger.LogInformation("你訪問了首頁");            _logger.LogWarning("警告資訊");            _logger.LogError("錯誤資訊");            return View();        }        public IActionResult About()        {            ViewData["Message"] = "Your application description page.";            return View();        }        public IActionResult Contact()        {            ViewData["Message"] = "Your contact page.";            return View();        }        public IActionResult Error()        {            return View();        }    }

使用DI 直接可以使用對象。

你會發現日誌資訊輸出來的是亂碼,這裡我們要指定輸出格式。

需要添加 System.Text.Encoding.CodePages 引用

Install-Package System.Text.Encoding.CodePages -Pre

然後在 Startup.cs —> Configure

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

這樣在控制台顯示就不會出現亂碼。

記錄層級:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical

層級包含範圍由大到小 ,如 Trace 就包含了所有資訊。

 

NLog 使用

 NLog 在 ASP.NET Core中的使用。

1.添加引用。

Install-Package NLog.Extensions.Logging -Pre

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="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-own-${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>

3.在 Startup.cs -》 Configure

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddNLog();//添加NLog

 

運行程式,你就會發現,項目下多了兩個檔案,證明成功執行。

這裡 nlog-all-*.log 是記錄所有日誌,nlog-own-*.log 記錄跳過Microsoft 開頭的類庫輸出的相關資訊,剩下的資訊。

 

4.發布(dotnet publish)注意事項

在 project.json 的  publishOptions節點 加入 nlog.config

  "publishOptions": {    "include": [      "wwwroot",      "Views",      "appsettings.json",      "web.config",      "nlog.config"//加上nlog設定檔    ]  },

 

GitHub :https://github.com/linezero/Blog/tree/master/NETCoreLogging

 

如果你覺得本文對你有協助,請點擊“推薦”,謝謝。

參考頁面:

http://www.yuanjiaocheng.net/Struts/first.html

http://www.yuanjiaocheng.net/mvc/area-in-asp.net-mvc.html

http://www.yuanjiaocheng.net/mvc/tempdata-in-asp.net-mvc.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-dbcontext.html

http://www.yuanjiaocheng.net/CSharp/csharp-partial-class.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-middleware.html

http://www.yuanjiaocheng.net/webapi/web-api-controller.html

http://www.yuanjiaocheng.net/mvc/mvc-helper-RadioButton.html

http://www.yuanjiaocheng.net/CSharp/first.html

http://www.yuanjiaocheng.net/mvc/mvc-controller.html

http://www.yuanjiaocheng.net/ASPNET-CORE/core-exception.html

ASP.NET Core 開發-Logging 使用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.