Tool:Visual Studio 2015 Ultimate Update 3
OS:Windows 10
.NET Framework : 4.6.x
ASP.NET MVC 5.x
本文簡述如何使用NLog來記錄MVC網站執行的資訊,將這些資訊寫到文字檔。
建立一個MVC範本專案測試
使用Package Manager Console安裝NLog
Install-Package NLog -Version 4.4.2
修改Web.config,加入藍色字的設定,設定Log檔案的檔名等相關資訊
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
<section name="nlog"
type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="default"
xsi:type="File"
fileName="weblogs/mylog.txt"
archiveFileName="weblogs/archives/mylog.{#}.txt"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="10" />
</targets>
<rules>
<logger name="*"
writeTo="default" />
</rules>
</nlog>
在程式中寫Log<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
<section name="nlog"
type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="default"
xsi:type="File"
fileName="weblogs/mylog.txt"
archiveFileName="weblogs/archives/mylog.{#}.txt"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="10" />
</targets>
<rules>
<logger name="*"
writeTo="default" />
</rules>
</nlog>
using NLog;
using System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger(); public ActionResult Index()
{
logger.Info("logger info...");
logger.Warn("logger warn...");
return View();
}
//以下略
按CTRL+ F5執行Home/Indexusing System.Web.Mvc;
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger(); public ActionResult Index()
{
logger.Info("logger info...");
logger.Warn("logger warn...");
return View();
}
//以下略
網站專案根目錄便會產生一個weblog資料夾,裏頭便會產生log檔案:
沒有留言:
張貼留言