What am I doing wrong? How to solve the linker error when trying to use the following class that inherits from basic_streambuf?
I am trying to use the example suggested here:
Redirect C++ std::clog to syslog on Unix
But I have a linker error: "undefined reference to `Log::Log(std::string, int)'"
[ERROR] /home/opmet/rgdias/pj_opmet/core/opmet-cpp/amhs-sender/target/nar/obj/amd64-Linux-gpp/main.63ebf91e.o: In function `main':
[ERROR] /home/opmet/rgdias/pj_opmet/core/opmet-cpp/amhs-sender/src/main/c++/main.cpp:52: undefined reference to `Log::Log(std::string, int)'
My code is doing something, like:
std::clog.rdbuf(new Log("foo", LOG_LOCAL0));
In order to use the class declared here:
#include <streambuf>
#include <syslog.h>
enum LogPriority {
kLogEmerg = LOG_EMERG, // system is unusable
kLogAlert = LOG_ALERT, // action must be taken immediately
kLogCrit = LOG_CRIT, // critical conditions
kLogErr = LOG_ERR, // error conditions
kLogWarning = LOG_WARNING, // warning conditions
kLogNotice = LOG_NOTICE, // normal, but significant, condition
kLogInfo = LOG_INFO, // informational message
kLogDebug = LOG_DEBUG // debug-level message
};
std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
class Log : public std::basic_streambuf<char, std::char_traits<char> > {
public:
explicit Log(std::string ident, int facility);
protected:
int sync();
int overflow(int c);
private:
friend std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority);
std::string buffer_;
int facility_;
int priority_;
char ident_[50];
};
#include <cstring>
#include <ostream>
#include "log.h"
Log::Log(std::string ident, int facility) {
facility_ = facility;
priority_ = LOG_DEBUG;
strncpy(ident_, ident.c_str(), sizeof(ident_));
ident_[sizeof(ident_)-1] = '\0';
openlog(ident_, LOG_PID, facility_);
}
int Log::sync() {
if (buffer_.length()) {
syslog(priority_, "%s", buffer_.c_str());
buffer_.erase();
priority_ = LOG_DEBUG; // default to debug for each message
}
return 0;
}
int Log::overflow(int c) {
if (c != EOF) {
buffer_ += static_cast<char>(c);
} else {
sync();
}
return c;
}
std::ostream& operator<< (std::ostream& os, const LogPriority& log_priority) {
static_cast<Log *>(os.rdbuf())->priority_ = (int)log_priority;
return os;
}