LoginSignup
37
46

More than 5 years have passed since last update.

【備忘録】NLog よく使う出力レイアウト

Posted at

はじめに

よく忘れちゃうので、明日の自分のためにメモっとく。

環境

  • Windows7 Professional SP1
  • Microsoft Visual Studio Version 12.0.31101.00 Update 4
  • Microsoft .NET Framework Version 4.5.51209
  • Microsoft Visual C# 2013
  • NLog 3.1.0.0

出力定義のポイント

  • スレッドIDは、8桁右寄せ
  • レベルは、5桁左寄せ
  • エンコーディングは、UTF-8
  • アーカイブは、日単位
  • アーカイブファイル名は、ローリング形式・固定名でナンバリングする
  • アーカイブは7日間

Example

Program.cs
    /// <summary>
    /// 【備忘録】NLog よく使う出力レイアウト
    /// </summary>
    class NLog02
    {
        private static NLog.Logger logger = NLog.LogManager.GetLogger("fooLogger");

        static void Main(string[] args)
        {
            try
            {
                logger.Trace("トレースログ");
                logger.Debug("デバッグログ");
                logger.Info("情報ログ");

                throw new Exception("エラーログ");
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
    }
NLog.config
  <targets>
    <target
      name="fooFile"
      xsi:type="File"
      layout="${longdate} [${threadid:padding=8}] [${uppercase:${level:padding=-5}}] ${callsite}() ${message} ${exception:format=tostring}"
      fileName="${basedir}/logs/${date:format=yyyyMMdd}.log"
      encoding="UTF-8"
      archiveFileName="${basedir}/logs/archives/archive.{#}.log"
      archiveEvery="Day"
      archiveNumbering="Rolling"
      maxArchiveFiles="7" />
  </targets>

  <rules>
    <logger name="fooLogger" minlevel="Trace" writeTo="fooFile" />
  </rules>
20150228.log
2015-02-28 19:11:46.2020 [       9] [TRACE] Shusaku.Examples.NLog02.Main() トレースログ 
2015-02-28 19:11:46.2190 [       9] [DEBUG] Shusaku.Examples.NLog02.Main() デバッグログ 
2015-02-28 19:11:46.2350 [       9] [INFO ] Shusaku.Examples.NLog02.Main() 情報ログ 
2015-02-28 19:11:46.2350 [       9] [ERROR] Shusaku.Examples.NLog02.Main() System.Exception: エラーログ
   場所 Shusaku.Examples.NLog02.Main(String[] args) 場所 c:\hoge\Examples\NLog02\NLog02\Program.cs:行 25 
37
46
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
37
46