Share a logfile between multiple services (each service with multiple threads), how to?
delphi, logging, multithreading
Solution
Your solution using a named mutex will work and is for sure the simplest approach.
Problem
I have this problem that I need to solve for one of my projects. I need to create ONE log file for 3 different services (don't ask why, my boss requested it like this). Each service can have multiple threads trying to log info into the file, so my question is, what's the best way to do this? Should I use a global mutex? Something like this: ``` procedure LogToFile(fn, str: string); var F: TextFile; begin logMutex.Acquire; try {$I+} try AssignFile(F, fn); if FileExists(fn) then Append(F) else Rewrite(F); Writeln(F, DateTimeToStr(Now) + ': ' + str); CloseFile(F); except end; {$I-} finally logMutex.Release; end; end; initialization logMutex := SyncObjs.TMutex.Create(nil, False,'some_global_mutex'); finalization logMutex.Free; ``` Any better ideas? Edit: Should I build another service, a logger service, that waits for messages that need to be logged from the other services and then only one service has to deal with the log files? If this is a good solution, what's the best way to communicate between services? I could use Indy...