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("*", LogLevel.Debug, fileTarget); logConfig.LoggingRules.Add(ruleFile); 31 //step5 Activate the configuration 32 LogManager.Configuration = logConfig; 33 }
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 }
4.调用方法验证
1 logger.Info("我在执行");
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