Multiple TFileStreams, TStreamWriter writing to same file

Viewed 215

I start using a TFileStream and TStreamWriter to write simple text logfiles (instead of old Writeln(T,....)). And I have multiple applicatiosn writing to the same logfile. Each appplication has its own TFileStream of course and they each open the file like this

FFileStream:=TFileStream.Create(LogName, fmOpenReadWrite+fmShareDenyNone)
FExporter:=TStreamWriter.Create(FFilestream, TEncoding.UTF8);
FExporter.NewLine:=#$0A;
FExporter.AutoFlush:=TRUE;

and write to the file with

  FExporter.BaseStream.Seek(0, soFromEnd);
  FExporter.Write('['+DateToStr(Now, FDateTimeFormat)+'] ['+TimeToStr(Now, FDateTimeFormat)+'] [#'+Lead0(GetCurrentThreadId, 5)+']: '+EntryText);
  FExporter.WriteLine;

the result is somewhat "unsatisfactory" as the lines are displaced, empty lines in between and does not seem to work.

HOW would I do that correctly?

1 Answers

Writing multiples lines at the same time in multiples process may result in unexpected continue, because parallels execution.

You should assure that you are writing a block continually so WriteLine shoud be send inside the write using lineBreak at the end.

So the way you can write should be:

  FExporter.BaseStream.Seek(0, soFromEnd);
  FExporter.Write('['+DateToStr(Now, FDateTimeFormat)+'] ['+TimeToStr(Now, FDateTimeFormat)+'] [#'+Lead0(GetCurrentThreadId, 5)+']: '+EntryText + System.slineBreak);
  //FExporter.WriteLine;

Update1: As the link Oliver posted, sometime it can not work if the message size to be written is bigger than the OS file sector and, at that very moment, other process also try to write a message. Thus in this case the result content might be mixed.

So doing what I first purpose you would increase the probability to have the desired result, but may not be the solution in 100% of the cases.

To be 100% sure of writing continuous log in a single file, using multiples process, you should create a log process to receive a message from the others and to be the only responsible for writing synchronized log throughout threads.

Related