0

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?

11
  • 1
    Where is Work() being called from? Is it a single thread? Are multiple applications writing to the file at the same time? Commented Dec 27, 2018 at 6:37
  • 1
    why are you flushing everytime after writing ? Commented Dec 27, 2018 at 6:42
  • 3
    This doesn't really look thread safe (even though we cant see the pertinent code) , i would hazard a guess if you changed your FileShare.ReadWrite to FileShare.Read you will get access errors due to 2 threads trying to get exclusive write access to the same file handle Commented Dec 27, 2018 at 6:45
  • remove writer.Flush(); you don't need if you using the keyword using Commented Dec 27, 2018 at 6:49
  • @John, Work() is called in single thread. In that situation, file used only by one instance of application. Commented Dec 27, 2018 at 6:53

1 Answer 1

3

@TheGeneral was right. I've got a lot of access exceptions. Mistake was in my calling code (several threads was created instead of one). Thanx all for help!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.