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?
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?
Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.
Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.
You could use the Apache log4net library:
You might want to use the Event Log ! Here's how to access it from C# http://support.microsoft.com/kb/307024/en
But whatever is the method that you will use, I'd recommend to output to a file every time something is appended to the log rather than when your process exits, so you won't lose data in the case of crash or if your process is killed.
add this config file
I'm using thread safe static class. Main idea is to queue the message on list and then save to log file each period of time, or each counter limit.
Important: You should force save file (
DirectLog.SaveToFile();
) when you exit the program. (in case that there are still some items on the list)The use is very simple:
DirectLog.Log("MyLogMessage", 5);
This is my code: