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 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.
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!
1. You may not assume that the buffers are null-terminated, don't use strlen()
2. When calling setp() you are replacing the previous buffer with your own.
This means that when syncing a second time you are reading and writing from the same buffer. Restore the old buffer after syncing.
3. You need a more thorough check for buffer overflow, make sure you're not writing past your buffer.
4. You may need a larger buffer if you're not going to sync often, otherwise the output will be truncated.
[Edit] You should sync after every message though, because the time written is the time of syncing, not the time the message was added to the log.
Bookmarks