问题描述
我正在写一个工具,将是检查工作站的运行状况通过网络,并且会根据发现问题的解决。我想创建一个日志文件中的应用程序是通过在每台机器上的任务/检查运行。我只是想获得一台机器上这个工作现在,但在时间它会一次过(螺纹出)来扫描100+机器。
I'm writing a tool that's going to be check the health of workstations across a network, and will fix according to the issues it finds. I want to create a log file as the app is running through its tasks / checks on each machine. I just want to get this working on a single machine for now, but in time it will be scanning 100+ machines in one go (Threaded out).
的 什么是创建日志文件的最好方法是什么?的
What is the best way to create a log file?
我想用名单,LT的;串>
建立在内存中的日志文件,然后输出到一旦它已经完成了文件
I was thinking of using a List<string>
to build up the log file in memory and then output it to a file once it had finished.
我只是在想。可能有这样做的更好的办法?
I'm just thinking there may be a better way of doing this?
推荐答案
我不会使用第三方库,我会登录到一个XML文件。
I would not use third party libraries, I would log to an xml file.
这是那些记录到来自不同线程的XML文件中的代码示例:
This is a code sample that do logging to a xml file from different threads:
private static readonly object Locker = new object();
private static XmlDocument _doc = new XmlDocument();
static void Main(string[] args)
{
if (File.Exists("logs.txt"))
_doc.Load("logs.txt");
else
{
var root = _doc.CreateElement("hosts");
_doc.AppendChild(root);
}
for (int i = 0; i < 100; i++)
{
new Thread(new ThreadStart(DoSomeWork)).Start();
}
}
static void DoSomeWork()
{
/*
* Here you will build log messages
*/
Log("192.168.1.15", "alive");
}
static void Log(string hostname, string state)
{
lock (Locker)
{
var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("host"));
el.SetAttribute("Hostname", hostname);
el.AppendChild(_doc.CreateElement("State")).InnerText = state;
_doc.Save("logs.txt");
}
}
这篇关于C#中的最佳方法来创建一个日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!