Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write log file in c#?

Tags:

c#

logging

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.

like image 803
user2725580 Avatar asked Nov 25 '13 04:11

user2725580


People also ask

What does .log mean on a file?

Log files are present in executable software, operating systems and programs whereby all the messages and process details are recorded.


2 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.

like image 95
evpo Avatar answered Sep 23 '22 09:09

evpo


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)         {         }     } } 
like image 26
SAR Avatar answered Sep 21 '22 09:09

SAR