CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2005
    Posts
    445

    Write to a log file

    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...

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Write to a log file

    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).

  3. #3
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Write to a log file

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured