NLog实现归档日志且只保留一段时间的日志(比如一个星期)

最近越来越发现NLog的好,我是用程序的方法来配置, 而不是用XML配置文件。

以下是代码,虽然麻烦了点,但是得到了我想要的功能。

   1:  using System;
   2:  using System.IO;
   3:  using System.Text;
   4:  using NLog;
   5:  using NLog.Config;
   6:  using NLog.Layouts;
   7:  using NLog.Targets;
   8:   
   9:  namespace ConsoleApplication1
  10:  {
  11:      public class LogHelper
  12:      {
  13:          private static string logPath = string.Empty;
  14:   
  15:          private static Logger loggerDebug = null;
  16:          private static Logger loggerTrace = null;
  17:   
  18:          public static void Debug(string log)
  19:          {
  20:              loggerDebug.Debug(log);
  21:          }
  22:   
  23:          public static void Trace(string log)
  24:          {
  25:              loggerTrace.Trace(log);
  26:          }
  27:   
  28:   
  29:   
  30:          public static bool Ready { get; set; }
  31:   
  32:   
  33:          static LogHelper() //静态构造方法,程序加载会执行一次
  34:          {
  35:              LogHelper.Ready = false;
  36:   
  37:              logPath = Path.Combine(new ConfigHelper().GetDesktopConfigPath(), "Log");
  38:              const string simpleLayout = @"${date:format=HH\:mm\:ss} | ${message} ${newline} | ${stacktrace} | ${newline} ${exception}";
  39:              //const string shortLayout = @"${date:format=HH\:mm\:ss} | ${message}";
  40:   
  41:              FileTarget fileTargetDebug = new FileTarget
  42:                  {
  43:                      Name = "DebugFile",
  44:                      MaxArchiveFiles = 7,
  45:                      ArchiveFileName = logPath + @"/archives/{###}_Debug.txt",
  46:                      ArchiveNumbering = ArchiveNumberingMode.Rolling,
  47:                      ArchiveEvery = FileArchivePeriod.Day,
  48:                      Layout = simpleLayout,
  49:                      AutoFlush = true,
  50:                      DeleteOldFileOnStartup = false,
  51:                      FileName = logPath + @"/Debug.txt",
  52:                      CreateDirs = true,
  53:                  };
  54:   
  55:              FileTarget fileTargetTrace = new FileTarget
  56:              {
  57:                  Name = "TraceFile",
  58:                  MaxArchiveFiles = 7,
  59:                  ArchiveFileName = logPath + @"/{###}_Trace.txt",
  60:                  ArchiveNumbering = ArchiveNumberingMode.Rolling,
  61:                  ArchiveEvery = FileArchivePeriod.Day,
  62:                  Layout = simpleLayout,
  63:                  AutoFlush = true,
  64:                  DeleteOldFileOnStartup = false,
  65:                  FileName = logPath + @"/Trace.txt",
  66:                  CreateDirs = true,
  67:              };
  68:   
  69:              //RichTextBoxTarget richTextBoxTarget = new RichTextBoxTarget();
  70:              //richTextBoxTarget.FormName = "FrmMain";
  71:              //richTextBoxTarget.ControlName = "DisplayBox";
  72:              //richTextBoxTarget.UseDefaultRowColoringRules = true;
  73:              //richTextBoxTarget.Layout = shortLayout;
  74:   
  75:              LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
  76:              loggingConfiguration.AddTarget("filedebug", fileTargetDebug);
  77:              loggingConfiguration.AddTarget("filetrace",fileTargetTrace);
  78:              //loggingConfiguration.AddTarget("richText", richTextBoxTarget);
  79:   
  80:   
  81:              //终于成功,日志只保留一个星期每天自动归档,且有大小限制。
  82:              LoggingRule ruleDebug = new LoggingRule("*", fileTargetDebug);
  83:              ruleDebug.EnableLoggingForLevel(LogLevel.Debug);
  84:   
  85:              LoggingRule ruleTrace = new LoggingRule("*", fileTargetTrace);
  86:              ruleTrace.EnableLoggingForLevel(LogLevel.Trace);
  87:   
  88:              loggingConfiguration.LoggingRules.Add(ruleDebug);
  89:              loggingConfiguration.LoggingRules.Add(ruleTrace);
  90:   
  91:              LogManager.Configuration = loggingConfiguration;
  92:              loggerDebug = LogManager.GetLogger("DebugFile");
  93:              loggerTrace = LogManager.GetLogger("TraceFile");
  94:   
  95:   
  96:              LogHelper.Ready = true;
  97:   
  98:          }
  99:   
 100:      }
 101:  }

该死,由于我用了ConfigHelper来取系统各种特殊目录,因此一起把代码贴出来,希望有所帮助,测试一般用桌面目录,用户日志一般正式发布的时候写到%AppData%下面, %ProgramData%这个目录慎用,一般用户没有写入权限的。

   1:  using System;
   2:  using System.Globalization;
   3:  using System.IO;
   4:   
   5:  namespace ConsoleApplication1
   6:  {
   7:      public class ConfigHelper
   8:      {
   9:          private readonly string desktopTemp = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  10:          private readonly string programdataTemp = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
  11:          private readonly string applicationdataTemp = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  12:   
  13:          public string GetFullPath(string basePath)
  14:          {
  15:              string temp = string.Empty;
  16:              temp = basePath + Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture);
  17:              temp += Path.GetFileNameWithoutExtension(System.Windows.Forms.Application.ExecutablePath);
  18:              temp += Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture);
  19:              return temp;
  20:          }
  21:   
  22:          public string GetDesktopConfigPath()
  23:          {
  24:              return GetFullPath(desktopTemp);
  25:          }
  26:   
  27:          public string GetAppDataConfigPath()
  28:          {
  29:              return GetFullPath(applicationdataTemp);
  30:          }
  31:   
  32:          public string GetProgramDataConfigPath()
  33:          {
  34:              return GetFullPath(programdataTemp);
  35:          }
  36:   
  37:      }
  38:  }

下面是调用的代码

   1:    class Program
   2:      {
   3:          static void Main(string[] args)
   4:          {
   5:              while (!LogHelper.Ready) ;
   6:              
   7:              //Create a thread write log continuously            
   8:              ThreadPool.QueueUserWorkItem(new WaitCallback(state =>
   9:                  {
  10:                      while (true)
  11:                      {
  12:                          LogHelper.Debug("this is a Test Debug! ");
  13:                          LogHelper.Trace("this is a Test Trace ! ");
  14:                          Thread.Sleep(20);
  15:                      }
  16:                  }));
  17:              Console.Read();
  18:   
  19:   
  20:   
  21:          }
  22:      }
原文地址:https://www.cnblogs.com/grkin/p/3133406.html