2015-12-17 114 views
0

我whant同時顯示NLog跟蹤到RichTextBox當應用程序執行顯示NLOG一絲的RichTextBox

logger.Trace("This is a Trace message"); 
logger.Debug("This is a Debug message"); 
logger.Info("This is an Info message"); 
logger.Warn("This is a Warn message"); 
logger.Error("This is an Error message"); 
logger.Fatal("This is a Fatal error message"); 

NLog任何全球性事件,這樣就可以使用它,並填充RichTextBox

謝謝!

+1

你見過這樣的:http://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_RichTextBoxTarget.htm –

+1

或https:// github.com/NLog/NLog/wiki/RichTextBox-target – stuartd

+1

or this http://stackoverflow.com/questions/16743804/implementing-a-log-viewer-with-wpf – Byron

回答

4

我們必須安裝https://www.nuget.org/packages/NLog.Windows.Forms

這種使用NLog.Windows.Forms;

後最後添加代碼

private void FormMain_Load(object sender, EventArgs e) 
     { 
      NLog.Windows.Forms.RichTextBoxTarget target = new NLog.Windows.Forms.RichTextBoxTarget(); 
      target.Name = "RichTextBox"; 
      target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}"; 
      target.ControlName = "richTextBoxMainLog"; 
      target.FormName = "FormMain"; 
      target.AutoScroll = true; 
      target.MaxLines = 10000; 
      target.UseDefaultRowColoringRules = false; 
      target.RowColoringRules.Add(
       new RichTextBoxRowColoringRule(
        "level == LogLevel.Trace", // condition 
        "DarkGray", // font color 
        "Control", // background color 
        FontStyle.Regular 
       ) 
      ); 
      target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control")); 
      target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control")); 
      target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control")); 
      target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold)); 
      target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold)); 

      AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper(); 
      asyncWrapper.Name = "AsyncRichTextBox"; 
      asyncWrapper.WrappedTarget = target; 

      SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace); 
     } 

還需要配置NLOG目標。

<target xsi:type="RichTextBox" 
      name="target2" 
      layout="${message} ${rtb-link:link text in config}" 

      formName="Form1" 
      ControlName="richTextBoxMainLog" 
      autoScroll="true" 
      maxLines="20" 

      allowAccessoryFormCreation="false" 
      messageRetention="OnlyMissed" 

      supportLinks="true" 

      useDefaultRowColoringRules="true" /> 

下載示例項目並對其進行測試https://github.com/NLog/NLog.Windows.Forms