LoginSignup
5
7

More than 5 years have passed since last update.

NLog覚書 インストールから設定まで

Last updated at Posted at 2017-02-22

ASP.netでWebアプリを開発している中、サーバーサイドで発生するエラーを確認する手段がなかったので、「NLog」を使う事になり、インストールから設定までを調査した内容を覚え書き。
もっと色々な設定が出来るみたいなのですが、今回は最低限の設定でシンプルに使っています。

参考サイト

https://github.com/nlog/nlog/wiki/Tutorial
http://news.mynavi.jp/articles/2010/03/19/nlog/
http://gomocool.net/gomokulog/?p=708
http://hkou.hatenablog.com/entry/2016/03/13/194043
http://dotnetcsharptips.seesaa.net/article/418697104.html

NLogとは

.NET環境でログ出力できるオープンソースのツール。
log4netに比べて導入が簡単なことが特徴。

使用環境

VisualStudio 2012
.NET Framework 4.5
NLog.4.4.3

インストール

VisualStudioのNuGetで簡単インストールしました。
1. ソリューションエクスプローラーの「参照設定」を右クリック
2. 下記のメニューが表示されるので、「NuGetパッケージの管理」をクリク
image
3. NuGetパッケージの管理画面が表示されるので、左側の「オンライン」をクリック後、右側の「オンラインの検索」に「NLog」を入力する
image
4. 真ん中に「NLog」が表示されるので、インストールボタンをクリックする
5. ソリューションエクスプローラーの「参照設定」の中に「NLog」があればインストール完了image

使用前に必要な設定

1. WebConfigのconfigSectionsへsectionタグを追加する

web.config
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>

  1. 引き続き、WebConfigにnlogタグを追加する
web.config
  <nlog>
    <targets>
      <target name ="logfile" type="File" filename="./Log/test.log" layout="[${longdate} ${level}]  ${message}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
  </nlog>

  taeget:出力先情報の設定
  layout:ログ出力レイアウトの設定
  rules:どの出力レベルに対しどのターゲットを使うかの設定

Level Example
Fatal Highest level: important stuff down
Error For example application crashes / exceptions.
Warn Incorrect behavior but the application can continue
Info Normal behavior like mail sent, user updated profile etc.
Debug Executed queries, user authenticated, session expired
Trace Begin method X, end method X etc

使い方

下記のように記述します。

sample.cs
using NLog;
    public class FileUploader : IHttpHandler
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public void ProcessRequest(HttpContext context)
        {
            // net use 接続
            System.Diagnostics.Process open = new System.Diagnostics.Process();
            open.StartInfo.FileName = "cmd.exe";            // コマンド名
            open.StartInfo.Arguments = "/c";                // 引数①
            open.StartInfo.Arguments += cmd;               // 引数②
            open.StartInfo.CreateNoWindow = true;           // DOSプロンプトの黒い画面を非表示
            open.StartInfo.UseShellExecute = false;         // プロセスを新しいウィンドウで起動するか否か
            open.StartInfo.RedirectStandardOutput = true;   // 標準出力をリダイレクトで取得したい
            open.Start();
            open.WaitForExit();

            logger.Debug("net use 接続");

出力結果

こんな感じに出力されました。
image

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7