Certain circumstances have forced me to write own simple logger. Method for writing entries into file runs in a separate thread and looks like this:
using System.Collections.Generic; using System.Collections.Concurrent; using System.IO; using System.Text; private ConcurrentQueue<Event> OccuredEvents { get; } private void Work() { using (FileStream fs = new FileStream (filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) { using (StreamWriter writer = new StreamWriter(fs)) { while (OccuredEvents.TryDequeue(out Event currentEvent)) { writer.WriteLine(currentEvent.ToString()); writer.Flush(); } } } } Sometimes in files appears some enries like that:
27.12.2018 08:49:13 [3e2291e2-a489-45ed-b169-fcc6b7bd1eda] [INFO] AcceptCallback - Client accepted (172.23.64.31:49820) :49:13 [3e2291e2-a489-45ed-b169-fcc6b7bd1eda] [INFO] GenerateResponse - AliveCommand | Data | AccountName: DOMAIN_KVC\07221147 or:
27.12.2018 08:49:13 [3e2291e2-a489-45ed-b169-fcc6b7bd1eda] [INFO] GenerateResponse - AliveCommand | Data | A27.12.2018 08:49:13 [3e2291e2-a489-45ed-b169-fcc6b7bd1eda] [INFO] AcceptCallback - Client accepted (172.23.7.86:49593) As seen, part of entry are lost or overlay another. Appearance of such anomalies is dependent on the number of entries. Apps with intense logging produce most of this "stubs".
What is my mistake? How to force StreamWriter to write full string into file?
Work()being called from? Is it a single thread? Are multiple applications writing to the file at the same time?FileShare.ReadWritetoFileShare.Readyou will get access errors due to 2 threads trying to get exclusive write access to the same file handlewriter.Flush();you don't need if you using the keywordusing