Question

I'm trying to write a log library which would use an external tool

i'm looking for convenient way to add Key-strings to the output stream to help parsing by the external tool while having the least impact on the programmer using the library

The goal is to achieved something like this:

cout << DEBUG::VERBOSE << "A should equal 3" << endl;
cout << DEBUG::WARNING << "something went wrong" << endl;

for now i structured my data as following

struct Debug
{
static const std::string FATAL_ERROR; 
static const std::string ERROR;
static const std::string WARNING;
static const std::string IMPORTANT;
static const std::string INFORMATION;
static const std::string VERBOSE;
static const std::string DEBUG;
};

this works find but i would like to add a level of abstraction from the std::string type.

In Java/C# i could would use an enum to achieve the write behavior, how can i implement this in C++ elegantly.

Was it helpful?

Solution

I think in C++ iostreams, stream manipulators in the style of endl are more idiomatic:

#include <iostream>

namespace debug
{
    std::ostream & info(std::ostream & os) { return os << "Info: "; }
    std::ostream & warn(std::ostream & os) { return os << "Warning: "; }
    std::ostream & error(std::ostream & os) { return os << "Error: "; }
}

int main()
{
    std::cout << debug::info << "This is main()\n"
              << debug::error << "Everything is broken\n";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top