microsoft / sfs-client

Simple File Solution (SFS) Client
MIT License
15 stars 13 forks source link

Consider streaming operators for logging #127

Closed arthuraraujo-msft closed 8 months ago

arthuraraujo-msft commented 8 months ago

Request by @JeffMill

Rather than:

    LOG_ERROR(handler,
              "FAILED [%s] %s (%s:%u)",
              code.c_str(),
              message.c_str(),
              file,
              line);

I'd like to see use of streaming which is type-safe (no argument matching, nor need to recall what formatter to use for a type, nor get number of args wrong). Heck, I feel strongly enough about this that I put together some working code:

e.g.

    LOG_ERROR(handler, 
              "FAILED [" << code << "] " << message << " (" << file << ":" << line << ")"
              );
#include <iostream>
#include <string>
#include <sstream>

class MessageStream
{
public:
    MessageStream(/*handler, severity*/) {}
    ~MessageStream()
    {
        /* handler_.LogWithSeverity(severity_, m_stream.str(), __FILE__, __LINE__, __FUNCTION__); */
        std::cout << "Message: " << m_stream.str() << std::endl;
    }
    template <typename T>
    MessageStream &operator<<(const T &value)
    {
        m_stream << value;
        return *this;
    }

private:
    std::ostringstream m_stream;
    // Handler handler_;
    // Severity severity_;
};

enum class LogSeverity
{
    Error
};

#define LOG_SEVERITY(handler, severity, format)       \
    do                                                \
    {                                                 \
        MessageStream stm; /* (handler, severity); */ \
        stm << format;                                \
    } while ((void)0, 0)

#define LOG_ERROR(handler, format) LOG_SEVERITY_STM(handler, LogSeverity::Error, format)

int main()
{
    std::string code{ "code" };
    std::string message{ "message" };
    const char* file{ "file" };
    unsigned int line{ 42 };

    void *handler = nullptr;

    LOG_ERROR(handler, "Hello,world!");

    LOG_ERROR(handler, "FAILED [" << code << "] " << message << " (" << file << ":" << line << ")");

    LOG_ERROR(handler, "SFSClient instance created successfully. Version: " << 3.14159265358979323846);

    return 0;
}