How would I write a log file in c#?
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.
Log files are present in executable software, operating systems and programs whereby all the messages and process details are recorded.
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 = new StringBuilder(); ... sb.Append("log something"); ... // flush every 20 seconds as you do it File.AppendAllText(filePath+"log.txt", sb.ToString()); sb.Clear();
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.
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.
create a class create a object globally and call this
using System.IO; using System.Reflection; public class LogWriter { private string m_exePath = string.Empty; public LogWriter(string logMessage) { LogWrite(logMessage); } public void LogWrite(string logMessage) { m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); try { using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt")) { Log(logMessage, w); } } catch (Exception ex) { } } public void Log(string logMessage, TextWriter txtWriter) { try { txtWriter.Write("\r\nLog Entry : "); txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); txtWriter.WriteLine(" :"); txtWriter.WriteLine(" :{0}", logMessage); txtWriter.WriteLine("-------------------------------"); } catch (Exception ex) { } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With