最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#中实现Log同时输出内容到文件和文本框(或终端)

C# crifan 14699浏览 0评论

【背景】

C#中,想要实现:

log系统

同时可以使得内容输出到两个地方:

log文件

文本框(中用于显示出来)或者是终端

 

同时,希望所引用的dll库(和相关文件)

能支持集成到winform的exe中。

使得别人拿到此程序,不会报错说找不到相关的dll库。

 

【解决过程】

1.参考:

How to write to an event log by using Visual C#

以及:

How to: Open and Append to a Log File

然后去看了看:

EventLog 类

和:

EventLog 类 – .NET Framework 4.5

发现不是我所需要的。

因为只是将内容输出到(windows系统中的)log中。

而不是可以指定某个文件或其他输出端的。

 

2.这里:

c# Best Method to create a log file

提到了:

NLog

有空去试试。

 

3.这里:

How to use logging in C# .NET projects?

介绍了如何使用log4net,貌似效果不错。

但是不知道是否可以同时输出内容到文本框同步显示。

 

4.参考:

C#第三方日志库Nlog

貌似Nlog是好用,但是貌似不支持同步输出到文本框显示。

 

5.参考:

NLog Custom Log Level Value

C# 使用Nlog记录日志到数据库

貌似可以通过overwrite对应的Append等函数,实现,同步输出内容到文本框?

 

6.然后通过:

NLog control to an existing RichTextBox Windows Form

找到了解决办法,是可以把输出弄到TextBox中的。

 

7.接着就可以去折腾Nlog了:

去:

NLog 2.0

下载:

NLog2.netcf35.zip

解压得到NLog.dll。

(之所以不去用NuGet去一次性都安装进来,是怕后期无法独立的集成对应的NLog.dll到当前的winform程序 ->发布给别人就没法独立运行了->会说缺少NLog.dll)

然后去把此dll加到项目中。

再参考:

C#第三方日志库Nlog

去添加Nlog Config

 

另外,可参考:

https://github.com/nlog/nlog/wiki

去看看各种Nlog官网的教程。

但是结果却打不开。。。

即使加了代理,页面却也是由于ssl证书有误,而Firefox拒绝打开。。。

所以算了。

 

8.后来也看到了别人:

How to use NLog for a DLL

提到说,如何使用Nlog的dll。

 

9.后来找到一个极其详尽的介绍Nlog的帖子:

Introduction to NLog

包括其中的,如何,不用配置文件,而通过代码配置的部分:

Programmatic configuration

 

所以,就参考这个,就足够了。

至于,担心,通过exe的installer去安装Nlog,而导致后来无法集成dll的问题,

就还是以后再说吧。

10.期间打开:Configuration API出错:

【已解决】Firefox报错:github.com 使用了无效的安全证书。 证书因为未提供证书发行链信而不被信任。 (错误码: sec_error_unknown_issuer)

11.然后发现,还是看官网的解释:

Configuration API

更清楚,其中就有对应的,多目标输出的示例代码。

然后参考着去写代码。

12.期间遇到:

【或许解决】C#中用Nlog结果找不到NLog.Win32

13.先记录一下:

https://github.com/nlog/nlog/wiki/Targets

中就提到了,支持Winform的TextBox的:

FormControl – Logs text to Windows.Forms.Control.Text property control of specified Name.
RichTextBox – Log text a Rich Text Box control in an existing or new form.
。。。

然后后来就真的,在API资料中,找到了对应的内容:

Nlog targets CloredConsoleTarget FileTarget RichTextBoxTarget

然后关于如何添加的话,是参考了:

http://nlog-project.org/documentation/v2.0.1/

而找到了:

LoggingConfiguration.AddTarget Method

的用法。

然后继续去写代码。

14.期间又遇到,关于RichTextBoxTarget始终新建窗口的问题:

【已解决】C#中用NLog的RichTextBoxTarget结果始终创建新窗口

15.然后再参考:

Layouts

去写Layout的值,找到了对应的date部分的设置:

https://github.com/nlog/nlog/wiki/Date-Layout-Renderer

 

然后所有的参数,包括basedir,date等的设置,都可以在:

Layout Renderers

找到:

${basedir} – The current application domain’s base directory.
${date} – Current date and time.
${level} – The log level.
${time} – The time in a 24-hour, sortable format HH:mm:ss.mmm.
${logger} – The logger name.
${counter} – A counter value (increases on each layout rendering).

 

16.期间又遇到别的事情:

C#的DateTime格式化成字符串

 

【总结】

最终,用了如下的代码:

private void initLogger()
{
    //logger = LogManager.GetCurrentClassLogger();

    // Step 1. Create configuration object 
    LoggingConfiguration logConfig = new LoggingConfiguration();

    // Step 2. Create targets and add them to the configuration 
    RichTextBoxTarget rtbTarget = new RichTextBoxTarget();
    logConfig.AddTarget("richTextBox", rtbTarget);
    rtbTarget.FormName = "frmScrapeAmazonProduct"; // your winform class name
    rtbTarget.ControlName = "rtbLog"; // your RichTextBox control/variable name

    FileTarget fileTarget = new FileTarget();
    logConfig.AddTarget("logFile", fileTarget);

    // Step 3. Set target properties
    string commonLayout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} ${logger} ${message}";
    rtbTarget.Layout = commonLayout;
    
    //string curDatetimeStr = DateTime.Now.ToString();
    DateTime curDateTime = DateTime.Now;
    string curDatetimeStr = String.Format("{0:yyyy-MM-dd_HHmmss}", curDateTime); //"2013-06-11_142102"
    fileTarget.FileName = "${basedir}/" + curDatetimeStr + "_log.txt"; //{'${basedir}/2013-06-11_142102_log.txt'}
    fileTarget.Layout = commonLayout;

    // Step 4. Define rules
    LoggingRule ruleRichTextBox = new LoggingRule("*", LogLevel.Debug, rtbTarget);
    logConfig.LoggingRules.Add(ruleRichTextBox);

    LoggingRule ruleFile = new LoggingRule("*", LogLevel.Debug, fileTarget);
    logConfig.LoggingRules.Add(ruleFile);

    // Step 5. Activate the configuration
    LogManager.Configuration = logConfig;

    // Example usage
    //Logger logger = LogManager.GetLogger("Amazon");
    Logger logger = LogManager.GetLogger("");
    logger.Trace("trace log message");
    logger.Debug("debug log message");
    logger.Info("info log message");
    logger.Warn("warn log message");
    logger.Error("error log message");
    logger.Fatal("fatal log message");
}

实现了自己要的效果:

文件的(文件名,是日期命名的):

file log effect with datetime name and log info

RichTextBox的:(同步输出到我们的RichTextBox中)

output log info to our richtextbox

 

【心得】

NLog,真心很强大,功能丰富。

也是很好用,感谢作者。

转载请注明:在路上 » 【已解决】C#中实现Log同时输出内容到文件和文本框(或终端)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.200 seconds, using 22.18MB memory