0

I encountered an issue when trying to log the content into the .txt file.

Below is my code. It will keep hit the exception as the process happen too fast. Is there anyway to write a queue to wait or a locker to lock the current thread first?

DateTime time = DateTime.Now;

time = time.Minute > 30 ? time.Date.AddHours(time.Hour).AddMinutes(30) : time.Date.AddHours(time.Hour).AddMinutes(0);

var FilePath = "C:/temp/DebugLog/"+ webService + "/" + time.ToString("yyyyMMddHHmss") + "_Logs/";

if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); }

try
{            
    using (StreamWriter w = File.AppendText(FilePath + time.ToString("yyyyMMddHHmss") + ".txt"))
    {
        w.WriteLine(
            Guid.NewGuid().ToString("N") + "; " + DateTime.Now.ToString("yyyyMMddHHmssms") + "; " +
            webService + "; " + eventName + "; " + DateTime.Now.ToString()  + "; " + transactionId + "; " + debuglog);
        w.Close();
    }
}
catch (Exception ex)
{

}
}
rene
  • 41,474
  • 78
  • 114
  • 152
Ah Chua
  • 9
  • 2
  • 3
    you can use "lock" if you want. but it will make things serial. Is that what you need ? Other approach could be append to a temporary buffer(concurrentbag) and have a separate thread write the contents of the buffer into a file every N seconds. – SRIDHARAN Sep 16 '22 at 08:14
  • 5
    Don't reinvent the wheel again. There are lots of logging libraries that manage concurrency for you – Jesús López Sep 16 '22 at 08:23
  • 1
    You really want separate log directories for every *second*? How will you be consuming these logs? – Damien_The_Unbeliever Sep 16 '22 at 08:26
  • @SRIDHARAN it could be serial, what I need just continuing writing it to the .txt and no error throw. – Ah Chua Sep 16 '22 at 08:27
  • @JesúsLópez is there any libraries that allow to customize the column? – Ah Chua Sep 16 '22 at 08:27
  • Serilog (https://serilog.net/) is very popular these days. – johey Sep 16 '22 at 08:29
  • Take a look at https://github.com/NLog/NLog/wiki/How-to-use-structured-logging – Jesús López Sep 16 '22 at 08:36
  • Aside from the mightily questionable usefulness of separate log directories _per_ second (as has already pointed out), do you really want separate log log files _per_ second as well? Also, allowing single-digit minutes in your file/directory names will make viewing them ordered by file names really fun... –  Sep 16 '22 at 08:38

0 Answers0