1. 程式人生 > WINDOWS開發 >C#NLog幫助類同時輸出內容到檔案和文字框

C#NLog幫助類同時輸出內容到檔案和文字框

1.引用NLog.dll檔案 2.在主窗體加入以下程式碼進行格式化 技術分享圖片
 1  //初始化程式碼
 2       private void Initlogger()
 3         {
 4             //step1.Create configuration object
 5             LoggingConfiguration logConfig = new LoggingConfiguration();
 6             //step2.create targets and add them to the configuration
 7             RichTextBoxTarget rtbTarget = new
RichTextBoxTarget(); 8 logConfig.AddTarget("richTextBox",rtbTarget); 9 rtbTarget.FormName = "Form1";//your winform class name 10 rtbTarget.ControlName = "richTextBox1";//your RichTextBox control/variable name 11 12 FileTarget fileTarget = new FileTarget();
13 logConfig.AddTarget("logFile",fileTarget); 14 15 //step3 Set target properties 16 string commonLayout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}${logger}${message}"; 17 rtbTarget.Layout = commonLayout; 18 19 DateTime curDateTime = DateTime.Now;
20 string curDatetimeStr = string.Format("{0:yyyy-MM-dd_HHmmss}",curDateTime); 21 22 // fileTarget.FileName = "${basedir}/" + curDatetimeStr + "_log.txt"; 23 fileTarget.FileName = "${basedir}/Logs/${shortdate}/log.csv"; 24 fileTarget.Layout = commonLayout; 25 26 //step4 Define rules 27 LoggingRule ruleRichTextBox = new LoggingRule("*",LogLevel.Debug,rtbTarget); 28 logConfig.LoggingRules.Add(ruleRichTextBox); 29 30 LoggingRule ruleFile = new LoggingRule("*",fileTarget); logConfig.LoggingRules.Add(ruleFile); 31 //step5 Activate the configuration 32 LogManager.Configuration = logConfig; 33 }
View Code 3.在窗體的Load事件中初始化程式碼 技術分享圖片
 1  public Logger logger;
 2         public Form1()
 3         {
 4             InitializeComponent();
 5         }
 6 
 7         private void Form1_Load(object sender,EventArgs e)
 8         {
 9             Initlogger();
10             logger = LogManager.GetLogger("");   
11         }
View Code 4.呼叫方法驗證 技術分享圖片
1   logger.Info("我在執行");
View Code 5.在其他類庫裡面使用的話,引用NLog.dll,不用Initlogger(),只需要獲取Logger 的例項化物件即可。 6.參考文章 技術分享圖片
1   https://www.crifan.com/csharp_implement_log_system_same_time_output_to_file_and_terminal/
2   
3   https://www.cnblogs.com/animal/articles/4073141.html
4   https://www.cnblogs.com/Can-daydayup/p/11182958.html
View Code