2

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?

Wolfgang Bures
  • 509
  • 4
  • 12
  • 2
    May I ask why you have several applications using the *same* log file? Anyway you'll need some kind of synchronization if you really want to do that. – Olivier Mar 05 '21 at 18:13
  • 3
    You can use a named mutex/semaphore to synchronize writes to the same log file, especially across process boundaries. – Remy Lebeau Mar 05 '21 at 18:52
  • 2
    modify your design, make a service that receives log entries via IPC and the service writes the log file – whosrdaddy Mar 06 '21 at 10:04

1 Answers1

-2

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.