如何用C#的日志文件? [英] How to write log file in c#?

查看:82
本文介绍了如何用C#的日志文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么会写在C#中的日志文件

How would I write a log file in c#?

目前我有这个声明,蜱每20秒的计时器:

Currently i have a timer with this statement which ticks every 20 secs:

File.WriteAllText(filePath+"log.txt", log);

有关,我想记录的一切,我做到这一点:

For everything that i want logged i do this:

log += "stringToBeLogged";



正如你可以假设字符串日志只是不停地生长在程序运行时。 (我甚至不知道是否有每串最大字符?)

As you can assume the string log just grows and grows as the program runs. (I don't even know if there is a maximum chars per string?)

我认为必须有这样做的更好的方法。我只是想,这将是沉重的一次又一次写入整个文件,为每个东西被添加到日志的时间。

I assume that there must be better ways of doing this. i just thought that it would be heavy to write the whole file again and again for every time something is added to the log.

推荐答案

从性能的角度来看你的解决方案不是最佳的。每次添加使用+ =,整个字符串被复制到内存中另一个地方另一个日志条目。我会建议使用StringBuilder的,而不是:

From the performance point of view your solution is not optimal. Every time you add another log entry with +=, the whole string is copied to another place in memory. I would recommend using StringBuilder instead:

StringBuilder sb;
...
sb.Append("log something");

...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();

这可能是另一个线程执行的计时器事件的方式。所以,你可能想访问你的 SB 对象时使用互斥。

By the way your timer event is probably executed on another thread. So you may want to use a mutex when accessing your sb object.

要考虑的另一件事是发生了什么执行的最后20秒内加入该日志条目。你可能要刷新您的字符串到应用程序退出前右侧的文件。

Another thing to consider is what happens to the log entries that were added within the last 20 seconds of the execution. You probably want to flush your string to the file right before the app exits.

这篇关于如何用C#的日志文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆