I have implemented a Logging class here.
class Log : public std::streambuf, public std::ostream {
public:
Log(int severity, const char* func, int line) :
std::ostream(this), severity_(severity) {
(this->severity_ == ERROR) ? std::cout << RED << "ERROR " :
std::cout << RESET << "INFO ";
std::cout << func << " @ line# " << line << ": ";
}
int overflow(int c) {
if (this->severity_ == ERROR) {
std::cout << RED;
std::cout.put((char) c);
} else {
std::cout.put((char) c);
}
return 0;
}
~Log() {
std::cout << RESET << std::endl;
}
private:
int severity_;
};
This works fine. But the output gets intermixed sometimes when two threads are executed concurrently. I went through several SO questions but they all discuss this in a broader way. I have this specific implementation which I want to fix. I tried adding a global mutex and calling this in a thread-safe way but the problem is that this file is a global header so cannot have a mutex variable defined globally here as it causes multiple definitions error. Is there any way to fix this?