Click to See Complete Forum and Search --> : Write to a log file


Salvadoravi
June 14th, 2008, 04:30 PM
Hi all,

What will be the best way to write errors to a log file in a multithreaded application?

Should I post a message that will write to the file from a single place, or should I build a function that lock the file write the error and release it? or maybe a different way..

Please help...

Arjay
June 14th, 2008, 08:26 PM
If you've seen some of my other posts, I like to keep messaging out of the threading solution as much as possible. I only use a message to signal the UI thread from the worker thread(s) that some event has happened. I never pass data in the message. For this logging scenario, there is no need to use messaging at all.

Given that, what I would do is create a LogMgr class that is accessed by the multiple threads. This class would be a singleton and expose a couple of methods like StartLogging, StopLogging, and various overloads of Log (which the secondary threads call when they want to log data).

The StartLogging method creates a secondary log processing thread that does the actual log file writing. The StopLogging method just causes the log processing thread to exit.

Log data is passed to the secondary thread using a std::queue (so this queue is shared between the threads). When worker threads call the Log( ) method, the log method locks the queue, pushes the log data onto the queue, unlocks the queue, and then sets a event to signal the log processing thread that data is in the queue. The log processing thread then wakes up, locks the queue, pulls the log item out of the queue, unlocks the queue, and writes the log data to the file.

The log method can be called simultaneously from any worker threads and the logs will be logged in sequential order.

As far as the logging data, I usually create a logging structure (that gets put into the queue). That way, I can track the message, priority, category, and other logging data).

exterminator
June 15th, 2008, 09:09 AM
May be use a thread-safe logging library? log4cpp/log4cplus are two libraries that I am aware of. For their thread-safety guarantees, you should refer to their project documentations.