ざっくりNLog

VisualStudio でログ出力をするなら、NLogがオススメ。

VisualStudio2013、VisualStudio2015なら、NuGetで簡単に導入できるようになっているので、「めんどくさいこと覚えずに、とにかくログを出したいんだ!」って方に本当にオススメ。

まず、NuGetパッケージの管理を起動

nlog-1

NLogをNuGetで探してインストール

nlog-2

nlog-3

参照にNLogがでればOK。

nlog-4

Web.configに以下の様な感じでconfigSectionsへsectionタグを追加し、nlogタグを追記する。

<configuration>
  <configSections>
    <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="logfile" xsi:type="File" fileName="C:\temp\nlogfile.txt" />
    </targets>
    <rules>
        <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
  </nlog>
</configuration>

使う場合は、下記のように記述。

//using NLog; 

Logger logger = LogManager.GetCurrentClassLogger();

logger.Trace("Sample trace message");
logger.Debug("Sample debug message");
logger.Info("Sample informational message");
logger.Warn("Sample warning message");
logger.Error("Sample error message");
logger.Fatal("Sample fatal error message");

logger.Log(LogLevel.Info, "Sample informational message");

return View();

nlogタグで設定した C:\temp\nlogfile.txt に、以下の様に出力される。

2015-11-20 11:25:48.6147|INFO|MvcLabo.Controllers.HomeController|Sample informational message
2015-11-20 11:25:48.6237|WARN|MvcLabo.Controllers.HomeController|Sample warning message
2015-11-20 11:25:48.6237|ERROR|MvcLabo.Controllers.HomeController|Sample error message
2015-11-20 11:25:48.6237|FATAL|MvcLabo.Controllers.HomeController|Sample fatal error message
2015-11-20 11:25:48.6237|INFO|MvcLabo.Controllers.HomeController|Sample informational message

以上。

超簡単。

 

Tips

○各.NetFrameworkごとにバージョンがあるようなので、途中で.NetFrameworkのバージョンを変えたりする場合は、再インストールしたほうが無難。

○かなり簡単に書いたけど、ログローテート、レベルによる切り分け、複数ログへの吐き出し、ファイルでなくデータベースへのログ吐き出しなど、使い切れてない機能がたくさんある。

○もちろん、Web.configでなく、デスクトップアプリ等のapp.configでも同じように使える。

 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>