Dear StackOverflowers,
I made a singleton class called Log
, but it does not call the constructor. The class is used to print Serial commands depending on m_LogLevel
. I want the constructor to be called once when getInstance()
is called for the first time. For some reason though, the constructor never seems to be called, what am I doing wrong?
Thanks in advance!
Log.h:
class Log {
private:
int m_LogLevel = LOGLEVEL;
static Log* instance;
Log();
~Log();
public:
static Log* getInstance();
void debug(String);
};
Log.cpp:
Log* Log::instance = nullptr;
Log::Log() {
DEBUG_PRINT("Log level: ");
DEBUG_PRINTLN(m_LogLevel);
}
Log::~Log() {
}
Log* Log::getInstance() {
if (instance == 0) {
instance = new Log();
}
return instance;
}
void Log::debug(String message) {
if(m_LogLevel >= LogLevelDebug) {
DEBUG_PRINT("[DEBUG]: ");
DEBUG_PRINTLN(message);
}
}
main.cpp:
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTLN(x) Serial.println (x)
#define LOGLEVEL 3
#include <Arduino.h>
#include "Log.h"
Log* pLog = Log::getInstance();
void setup() {
Serial.begin(115200);
pLog->debug("Hello world");
}
void loop() {
}