Boost logo

Boost Users :

From: Ani Taggu (yg-boost-users_at_[hidden])
Date: 2002-09-02 06:02:04


Hello:

I have a simple class to do simple thread-safe logging using recursive_mutex
as shown below. The problem is, once in a while, it causes any thread to die
while it tries to log. I haven't been able to isolate why this happens. Is
recursive_mutex being used correctly?

The logging is done like so:

extern FileLogger &TheLog()
{
    static g_log("my.log");
   return g_log;
}

TheLog() << "Hello World" << endl;

I am using boost 1_28 with MSVC 6 SP5.

----------------------------------------------------------------------------
------------------

#include <fstream>
#include <string>
#include "boost/thread/recursive_mutex.hpp"

class FileLogger
{
public:

 // set second arg = false to do no logging.
 FileLogger(const std::string &logName, bool log=true) : log_(log)
 {
  if (log_)
  {
   strm_.open(logName.c_str(), std::ios::ate);
  }
 }

 // logging can be accessed from any thread.
 template <typename T>
  std::ostream & operator<< (T d)
 {
  if (log_)
  {
   boost::recursive_mutex::scoped_lock l(strmMutex_);
   strm_ << d;
  }
  return strm_;
 }

 ~FileLogger()
 {
  if (log_)
  {
   strm_.close();
  }
 }

private:
 std::ofstream strm_;
 boost::recursive_mutex strmMutex_;
 bool log_;
};


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net