Question

POCO::Logger have class called LogStream who implement a ostream for a logger.

Im trying to write a class wrapper to implement a log system for my project.

so far i have this:

the h.

#include "Poco/LogStream.h"
#include "Poco/Logger.h"
#include "Poco/FileChannel.h"
#include "Poco/AutoPtr.h"

using Poco::Logger;
using Poco::FileChannel;
using Poco::AutoPtr;
using Poco::LogStream;

class MyLogger
{
public:
    MyLogger();
    Poco::LogStream& operator()();
    ~MyLogger();

private:
    Poco::Logger& m_logger;
 };

the cpp

  MyLogger::MyLogger() : m_logger(Poco::Logger::get(APP_NAME))
  {
/*
 AutoPtr<FileChannel> pChannel(new FileChannel);
 pChannel->setProperty("path", "c:\\teshss.log");
 pChannel->setProperty("rotation", "2 K");
 pChannel->setProperty("archive", "timestamp");

 Logger::root().setChannel(pChannel);
 Logger& logger = Logger::get(APP_NAME); // inherits root channel
*/
  }

  Poco::LogStream& MyLogger::operator()()
  {
AutoPtr<FileChannel> pChannel(new FileChannel);
pChannel->setProperty("path", "c:\\teshss.log");
pChannel->setProperty("rotation", "2 K");
pChannel->setProperty("archive", "timestamp");

Logger::root().setChannel(pChannel);
Logger& logger = Logger::get("");
LogStream lstr(logger);
return lstr;
  }

  MyLogger::~MyLogger()
  {
  }

then on my project, first i generate a instance for MyLogger:

   MyLogger mylog;

and inside a function:

   mylog() << "Hello world" << std::endl;

This code complile and run, but generate an access violation when i try to write a log line.

Honestly, i dont have to much idea about what im doing, I have experience working with C++, but write a wrapper is totally new for me. So I need some help.

thanks.

Was it helpful?

Solution

Returning reference to stack-created value is undefined behavior:

Poco::LogStream& MyLogger::operator()()
{
//...
  LogStream lstr(logger);
  return lstr;
}

LogStream must outlive the execution of operator(); try something along these lines:

class MyLogger
{
public:
  MyLogger(): lstr(0) /* ... */ { }
  ~MyLogger() { delete lstr; }
  // ...
  Poco::LogStream& operator()()
  {
  // ...
   if (!lstr) lstr = new LogStream(logger)
   return *lstr;
  }
private:
  LogStream* lstr;
};

If operator() is called from multiple threads, you should shield the LogStream creation time with a Mutex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top