Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 176
  • Last Modified:

Log file

I have application base on paradox with multi threads.
I wish to make log file (Ascii).

what is the best way to open / write an ascii file ?

I prefer that the methods will threads safe ...

10
Asi

0
asi
Asked:
asi
1 Solution
 
edsteeleCommented:
Unless you are using an object with built in locking, you will probably need to use a TCriticalSection object.


...

var
  MyLogLock: TCriticalSection

...

  MyLogLock := TCriticalSection.Create;

...

MyLogLock.Acquire; { lock out other threads }

try
  { Do your log functions here! }
finally
  MyLogLock.Release;
end;

My suggestion for opening and writing to the ASCII file would be to use a TStringStream.  Allow the threads to write to an intermediate location (a TStringList, maybe) and have the main application thread be in charge of periodic log updates.  CAUTION: Remember to acquire a lock from MyLogLock before doing this so the threads don't try to update the TStringList while the main thread is reading from it.

The code for using TStringStream in this case is very easy:

procedure UpdateLogFile;
var
  MyStream: TStringStream;
  i: Integer;
begin
  MyStream := TStringStream.Create('C:\Logs\MyApp.log');
  try
    MyStream.Seek(0, soFromEnd);

    MyLogLock.Acquire; { lock out other threads }

    try
      for i := 0 to LogList.Count - 1 do
        MyStream.WriteString(LogList[i]);
      LogList.Clear;
    finally
      MyLogLock.Release;
    end;
  finally
    MyStream.Free;
  end;
end;

Good Luck!
Eric
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now