How to write log file in c#?

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.

1

11 Answers

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.

2

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) { } }
}
4

Use File.AppendAllText instead:

File.AppendAllText(filePath + "log.txt", log);
6
public static void WriteLog(string strLog) { StreamWriter log; FileStream fileStream = null; DirectoryInfo logDirInfo = null; FileInfo logFileInfo; string logFilePath = "C:\\Logs\\"; logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt"; logFileInfo = new FileInfo(logFilePath); logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName); if (!logDirInfo.Exists) logDirInfo.Create(); if (!logFileInfo.Exists) { fileStream = logFileInfo.Create(); } else { fileStream = new FileStream(logFilePath, FileMode.Append); } log = new StreamWriter(fileStream); log.WriteLine(strLog); log.Close(); } 

Refer Link:blogspot.in

1

Add log to file with Static Class

 public static class LogWriter { private static string m_exePath = string.Empty; public static void LogWrite(string logMessage) { m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!File.Exists(m_exePath + "\\" + "log.txt")) File.Create(m_exePath + "\\" + "log.txt"); try { using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt")) AppendLog(logMessage, w); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private static void AppendLog(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) { } } }
2

as posted by @randymohan, with using statements instead

public static void WriteLog(string strLog)
{ string logFilePath = @"C:\Logs\Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt"; FileInfo logFileInfo = new FileInfo(logFilePath); DirectoryInfo logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName); if (!logDirInfo.Exists) logDirInfo.Create(); using (FileStream fileStream = new FileStream(logFilePath, FileMode.Append)) { using (StreamWriter log = new StreamWriter(fileStream)) { log.WriteLine(strLog); } }
}
2

Very convenient tool for logging is

You can also make something of themselves less (more) powerful. You can use (v = vs.110). Aspx

1
if(!File.Exists(filename)) //No File? Create
{ fs = File.Create(filename); fs.Close();
}
if(File.ReadAllBytes().Length >= 100*1024*1024) // (100mB) File to big? Create new
{ string filenamebase = "myLogFile"; //Insert the base form of the log file, the same as the 1st filename without .log at the end if(filename.contains("-")) //Check if older log contained -x { int lognumber = Int32.Parse(filename.substring(filename.lastIndexOf("-")+1, filename.Length-4); //Get old number, Can cause exception if the last digits aren't numbers lognumber++; //Increment lognumber by 1 filename = filenamebase + "-" + lognumber + ".log"; //Override filename } else { filename = filenamebase + "-1.log"; //Override filename } fs = File.Create(filename); fs.Close();
}

Refer link:

This is add new string in the file

using (var file = new StreamWriter(filePath + "log.txt", true)) { file.WriteLine(log); file.Close(); }

There are 2 easy ways

  • StreamWriter -
  • Log4Net like Log4j(Java) -

If your application is multithreaded then in some environments file.appendalltext could give error like file already in use and if you skip that then you could lose important logs . For that you can use Lock object technique with file.append.. in that case it will wait for existing process to close and the write your log

This can also save you from adding other libraries in your source

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like