c# Best Method to create a log file

前端 未结 12 611
甜味超标
甜味超标 2020-12-28 13:37

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

12条回答
  •  一向
    一向 (楼主)
    2020-12-28 13:47

    I would not use third party libraries, I would log to an xml file.

    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");
        }
    }
    

提交回复
热议问题