Sensor3/lib/patrix/log.cpp

62 lines
1.4 KiB
C++

#include <HardwareSerial.h>
#include "log.h"
#include "mqtt.h"
#define SEPARATOR " | "
bool debugEnabled = false;
void getDateTime(char *buffer, size_t size) {
time_t now;
time(&now);
tm time{};
localtime_r(&now, &time);
strftime(buffer, size, "%Y-%m-%d %H:%M:%S %z", &time);
}
void log(const char *level, const char *module, const char *format, ...) {
char datetime[26];
getDateTime(datetime, sizeof datetime);
va_list vl;
va_start(vl, format);
char message[500];
vsnprintf(message, sizeof message, format, vl);
va_end(vl);
const size_t len = Serial.print(datetime) + Serial.print(SEPARATOR) + Serial.print(module) + Serial.print(SEPARATOR) + Serial.print(level) + Serial.print(SEPARATOR) + Serial.print(message) + Serial.println();
mqttPublishLog(len, SEPARATOR, datetime, module, level, message);
}
void debug(const char *module, const char *format, ...) {
if (!debugEnabled) {
return;
}
va_list vl;
va_start(vl, format);
log("DEBUG", module, format, vl);
va_end(vl);
}
void info(const char *module, const char *format, ...) {
va_list vl;
va_start(vl, format);
log("INFO", module, format, vl);
va_end(vl);
}
void error(const char *module, const char *format, ...) {
va_list vl;
va_start(vl, format);
log("ERROR", module, format, vl);
va_end(vl);
}
void setDebugEnabled(const bool enabled) {
debugEnabled = enabled;
}
bool isDebugEnabled() {
return debugEnabled;
}