dear friends,

I am developing a simple log stream class by deriving and over-riding ostream and streambuf classes. The purpose of this class is to provide insertion operator (<<) kind of syntax for logging messages. In addition, this class inserts a date string automatically to every new line.

The code of this class is given here:

Code:
#include <ostream>
#include <fstream>
#include <iostream>
#include <cstring>
using namespace std;

class LogBuf : public filebuf {
 
public:
    LogBuf(const char* file) : bNewLine_(true), writeP_(0) {
        open(file, ios::out);
    }   

    int sync() {
        cout << "syncing..." << endl;
        long len = strlen(pbase());
        if (len > 0) processDate('\n');
        int iRet = filebuf::sync();

        reset();
        return iRet;
    }   

    void processDate(int ch) {

        char* bufs;
        time_t t;
        struct tm* timeinfo;
        time(&t);
        timeinfo = localtime(&t);
        bufs = pbase();

        cout << "date processing..." << endl;
        size_t contentLen = strlen(bufs) + 1;

        for (size_t i=0; i<contentLen;  ++i) {
            if (bNewLine_) {
                writeP_ += strftime(buf_+writeP_, (sizeof(buf_)-writeP_), "[%Y%m%d-%H%M%S] ", timeinfo);
                bNewLine_ = !bNewLine_;
            }
            if (bufs[i] == '\n') bNewLine_ = true;
            buf_[writeP_++] = bufs[i];
        }

        setp(buf_, buf_+writeP_);
        pbump(writeP_);
    }

    ~LogBuf() {
        cout << "LogBuf::destructor at work..." << endl;
        sync();
    }

private:
    char buf_[1024];
    bool bNewLine_;
    size_t writeP_;

    void reset() {
        memset(buf_, 0x00, sizeof(buf_));
        writeP_ =0;
    }
};


class DebugStream : private LogBuf, public ostream {
public:
    DebugStream(const char* file):LogBuf(file), ostream (this) { }
};

- The above program has two classes DebugStream and LogBuf.
- LogBuf's processDate() method scans the output string and inserts a date string after every new line character.

and, the test code is like this.

Code:
#include "Rsdpdebug.hpp"

int main(int argc, char** argv) {

    DebugStream ds ("log.log");
    ds << "Hello first logger world!" << "\n" ;
    ds << "Hello second logger world!" << '\n';
    ds << "Hello third logger world!" ;
    ds << "Hello fourth logger world!" << endl;
}

The problem is that
- If in the test code, no "endl" is given, then the 'sync()' never gets called, and so the method processDate() is never called.
- On the other hand, if an endl is given, the output is repeated multiple times like this below...

20100809-072039] Hello first logger world!
[20100809-072039] Hello second logger world!
[20100809-072039] Hello third logger world!Hello fourth logger world!
[20100809-072039] Hello first logger world!
[20100809-072039] Hello second logger world!
[20100809-072039] Hello third logger world!Hello fourth logger world!
Can anyone suggest what is going wrong in here...

thanks in advance,
RV