c++iostreamcoutstreambuf

std::clog wrapper with color and header fails to print integers properly


I need a class to wrap calls to std::clog so that:

My attempt has been based on many examples found in this forum (*), but I guess in a kind of a wrong way, because my class is a bit faulty. Essentially what I tried is to extend std::streambuf by overriding the overflow and xputn methods in a way that they end up calling clog's operator<<.

NB: I found it difficult to keep my question complete(**), minimal and verifiable all at the same time, so any suggestions/comments on that will be much appreciated. What matters most to me, though, is the approach I have taken rather than the specific bugs or implementation flaws.

class LogStream : public std::streambuf
{
public:
    enum class Color { RED_BRIGHT, RED_DARK, /* ...others */ NO_COLOR };

    LogStream(void);
    LogStream(std::basic_ostream<char>& out, std::string cname, char c, Color icon_color, Color text_color = Color::NO_COLOR);

    /* Non-copiable. */
    LogStream(const LogStream&) = delete;
    LogStream& operator=(const LogStream&) = delete;

    static void setNameLength(int l);

protected:
    int_type overflow(int_type c = traits_type::eof());
    std::streamsize xsputn(const char* s, std::streamsize n);

private:
    /* Important stuff: */
    std::basic_ostream<char>& m_out;
    bool m_new_line;

    void conditionalPrintHeader(void);
    void endLine(void);

    /* For message decoration purposes: */
    Color m_color_icon;
    Color m_color_text;
    char m_icon;
    std::string m_cname;
    static std::map<Color, const std::string> m_color_lut;
};

/* A macro to create static instances of a logger later in each CPP file. */
#define CREATE_LOGGER(klass)                        \
    namespace Log {                                 \
        static std::ostream dbg(new LogStream(      \
            std::clog,                              \
            #klass,                                 \
            '>',                                    \
            LogStream::Color::RED_BRIGHT,           \
            LogStream::Color::NO_COLOR));           \
        static std::ostream err(new LogStream(      \
            std::clog,                              \
            #klass,                                 \
            'e',                                    \
            LogStream::Color::RED_BRIGHT,           \
            LogStream::Color::RED_DARK));           \
    }

My overridden functions are implemented like so:

std::streamsize LogStream::xsputn(const char* s, std::streamsize n)
{
    conditionalPrintHeader();
    if(s[n - 1] == '\n') {
        m_new_line = true;
        endLine();
    }
    m_out << s;
    return n;
}

LogStream::int_type LogStream::overflow(int_type c)
{
    if(c == traits_type::eof()) {
        return traits_type::eof();
    } else {
        char_type ch = traits_type::to_char_type(c);
        return xsputn(&ch, 1) == 1 ? c : traits_type::eof();
    }
}

void LogStream::conditionalPrintHeader(void)
{
    if(m_new_line) {
        m_out << "... header and color escape codes ...";
        m_new_line = false;
    }
}

void LogStream::endLine(void)
{
    m_out << "color escape code for no color.";
}

The functions conditionalPrintHeader and endLine essentially try to implement this basic structure:

[header string] [ANSI color code] [<the log message>] [end color code]

So that when I do:

Log::warn << "Integer: " << 123 << ", Bool: " << std::boolalpha << true << ", Float: " << 3.1415f << "\n";

The terminal outputs:

HEADER + [START COLOR] Integer: 123, Bool: true, Float: 3.1415 [END COLOR]

Most of the time everything works great except when I need to print integer values. Instead of the number, I get additional garbage, like so:

[ ... ] Integer: 123�~c, Bool: true, Float: 3.1415

Notes:

(*) Similar questions that inspired or directly contributed to my solution:

(**) I pasted the whole header and source files in order to be as complete as possible and in case I'm missing the error somewhere else: Log.hpp, Log.cpp.


Solution

  • For now I considered that the problem laid in the character string argument of xsputn (which I assumed is not null-terminated). I solved my issue with integers like as follows, but I'm still unclear whether the approach is good or not.

    std::streamsize LogStream::xsputn(const char* s, std::streamsize n)
    {
        conditionalPrintHeader();
        if(s[n - 1] == '\n') {
            m_new_line = true;
            endLine();
        }
        std::string str;
        for(int c = 0; c < n; c++) {
            str += s[c];
        }
        m_out << str;
        return n;
    }