ClassLogFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #include "ClassLogFile.h"
  2. #include "time_sntp.h"
  3. #include "esp_log.h"
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <algorithm>
  8. #ifdef __cplusplus
  9. extern "C" {
  10. #endif
  11. #include <dirent.h>
  12. #ifdef __cplusplus
  13. }
  14. #endif
  15. #include "Helper.h"
  16. #include "time_sntp.h"
  17. #include "../../include/defines.h"
  18. static const char *TAG = "LOGFILE";
  19. ClassLogFile LogFile("/sdcard/log/message", "log_%Y-%m-%d.txt", "/sdcard/log/data", "data_%Y-%m-%d.csv");
  20. void ClassLogFile::WriteHeapInfo(std::string _id)
  21. {
  22. if (loglevel >= ESP_LOG_DEBUG) {
  23. std::string _zw = _id + "\t" + getESPHeapInfo();
  24. WriteToFile(ESP_LOG_DEBUG, "HEAP", _zw);
  25. }
  26. }
  27. void ClassLogFile::WriteToData(std::string _timestamp, std::string _name, std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ReturnRateValue, std::string _ReturnChangeAbsolute, std::string _ErrorMessageText, std::string _digit, std::string _analog)
  28. {
  29. ESP_LOGD(TAG, "Start WriteToData");
  30. time_t rawtime;
  31. struct tm* timeinfo;
  32. char buffer[30];
  33. time(&rawtime);
  34. timeinfo = localtime(&rawtime);
  35. strftime(buffer, 30, datafile.c_str(), timeinfo);
  36. std::string logpath = dataroot + "/" + buffer;
  37. FILE* pFile;
  38. std::string zwtime;
  39. ESP_LOGD(TAG, "Datalogfile: %s", logpath.c_str());
  40. pFile = fopen(logpath.c_str(), "a+");
  41. if (pFile!=NULL) {
  42. fputs(_timestamp.c_str(), pFile);
  43. fputs(",", pFile);
  44. fputs(_name.c_str(), pFile);
  45. fputs(",", pFile);
  46. fputs(_ReturnRawValue.c_str(), pFile);
  47. fputs(",", pFile);
  48. fputs(_ReturnValue.c_str(), pFile);
  49. fputs(",", pFile);
  50. fputs(_ReturnPreValue.c_str(), pFile);
  51. fputs(",", pFile);
  52. fputs(_ReturnRateValue.c_str(), pFile);
  53. fputs(",", pFile);
  54. fputs(_ReturnChangeAbsolute.c_str(), pFile);
  55. fputs(",", pFile);
  56. fputs(_ErrorMessageText.c_str(), pFile);
  57. fputs(_digit.c_str(), pFile);
  58. fputs(_analog.c_str(), pFile);
  59. fputs("\n", pFile);
  60. fclose(pFile);
  61. } else {
  62. ESP_LOGE(TAG, "Can't open data file %s", logpath.c_str());
  63. }
  64. }
  65. void ClassLogFile::setLogLevel(esp_log_level_t _logLevel)
  66. {
  67. std::string levelText;
  68. // Print log level to log file
  69. switch(_logLevel) {
  70. case ESP_LOG_WARN:
  71. levelText = "WARNING";
  72. break;
  73. case ESP_LOG_INFO:
  74. levelText = "INFO";
  75. break;
  76. case ESP_LOG_DEBUG:
  77. levelText = "DEBUG";
  78. break;
  79. case ESP_LOG_ERROR:
  80. default:
  81. levelText = "ERROR";
  82. break;
  83. }
  84. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Set log level to " + levelText);
  85. // set new log level
  86. loglevel = _logLevel;
  87. /*
  88. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Test");
  89. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Test");
  90. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Test");
  91. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Test");
  92. */
  93. }
  94. void ClassLogFile::SetLogFileRetention(unsigned short _LogFileRetentionInDays){
  95. logFileRetentionInDays = _LogFileRetentionInDays;
  96. }
  97. void ClassLogFile::SetDataLogRetention(unsigned short _DataLogRetentionInDays){
  98. dataLogRetentionInDays = _DataLogRetentionInDays;
  99. }
  100. void ClassLogFile::SetDataLogToSD(bool _doDataLogToSD){
  101. doDataLogToSD = _doDataLogToSD;
  102. }
  103. bool ClassLogFile::GetDataLogToSD(){
  104. return doDataLogToSD;
  105. }
  106. static FILE* logFileAppendHandle = NULL;
  107. std::string fileNameDate;
  108. void ClassLogFile::WriteToFile(esp_log_level_t level, std::string tag, std::string message, bool _time)
  109. {
  110. time_t rawtime;
  111. struct tm* timeinfo;
  112. std::string fileNameDateNew;
  113. std::string zwtime;
  114. std::string ntpTime = "";
  115. time(&rawtime);
  116. timeinfo = localtime(&rawtime);
  117. char buf[30];
  118. strftime(buf, sizeof(buf), logfile.c_str(), timeinfo);
  119. fileNameDateNew = std::string(buf);
  120. std::replace(message.begin(), message.end(), '\n', ' '); // Replace all newline characters
  121. if (tag != "") {
  122. ESP_LOG_LEVEL(level, tag.c_str(), "%s", message.c_str());
  123. message = "[" + tag + "] " + message;
  124. }
  125. else {
  126. ESP_LOG_LEVEL(level, "", "%s", message.c_str());
  127. }
  128. if (level > loglevel) {// Only write to file if loglevel is below threshold
  129. return;
  130. }
  131. if (_time)
  132. {
  133. char logLineDate[30];
  134. strftime(logLineDate, sizeof(logLineDate), "%Y-%m-%dT%H:%M:%S", timeinfo);
  135. ntpTime = std::string(logLineDate);
  136. }
  137. std::string loglevelString;
  138. switch(level) {
  139. case ESP_LOG_ERROR:
  140. loglevelString = "ERR";
  141. break;
  142. case ESP_LOG_WARN:
  143. loglevelString = "WRN";
  144. break;
  145. case ESP_LOG_INFO:
  146. loglevelString = "INF";
  147. break;
  148. case ESP_LOG_DEBUG:
  149. loglevelString = "DBG";
  150. break;
  151. case ESP_LOG_VERBOSE:
  152. loglevelString = "VER";
  153. break;
  154. case ESP_LOG_NONE:
  155. default:
  156. loglevelString = "NONE";
  157. break;
  158. }
  159. std::string formatedUptime = getFormatedUptime(true);
  160. std::string fullmessage = "[" + formatedUptime + "] " + ntpTime + "\t<" + loglevelString + ">\t" + message + "\n";
  161. #ifdef KEEP_LOGFILE_OPEN_FOR_APPENDING
  162. if (fileNameDateNew != fileNameDate) { // Filename changed
  163. // Make sure each day gets its own logfile
  164. // Also we need to re-open it in case it needed to get closed for reading
  165. std::string logpath = logroot + "/" + fileNameDateNew;
  166. ESP_LOGI(TAG, "Opening logfile %s for appending", logpath.c_str());
  167. logFileAppendHandle = fopen(logpath.c_str(), "a+");
  168. if (logFileAppendHandle==NULL) {
  169. ESP_LOGE(TAG, "Can't open log file %s", logpath.c_str());
  170. return;
  171. }
  172. fileNameDate = fileNameDateNew;
  173. }
  174. #else
  175. std::string logpath = logroot + "/" + fileNameDateNew;
  176. logFileAppendHandle = fopen(logpath.c_str(), "a+");
  177. if (logFileAppendHandle==NULL) {
  178. ESP_LOGE(TAG, "Can't open log file %s", logpath.c_str());
  179. return;
  180. }
  181. #endif
  182. fputs(fullmessage.c_str(), logFileAppendHandle);
  183. #ifdef KEEP_LOGFILE_OPEN_FOR_APPENDING
  184. fflush(logFileAppendHandle);
  185. fsync(fileno(logFileAppendHandle));
  186. #else
  187. CloseLogFileAppendHandle();
  188. #endif
  189. }
  190. void ClassLogFile::CloseLogFileAppendHandle() {
  191. if (logFileAppendHandle != NULL) {
  192. fclose(logFileAppendHandle);
  193. logFileAppendHandle = NULL;
  194. fileNameDate = "";
  195. }
  196. }
  197. void ClassLogFile::WriteToFile(esp_log_level_t level, std::string tag, std::string message) {
  198. LogFile.WriteToFile(level, tag, message, true);
  199. }
  200. std::string ClassLogFile::GetCurrentFileNameData()
  201. {
  202. time_t rawtime;
  203. struct tm* timeinfo;
  204. char buffer[60];
  205. time(&rawtime);
  206. timeinfo = localtime(&rawtime);
  207. strftime(buffer, 60, datafile.c_str(), timeinfo);
  208. std::string logpath = dataroot + "/" + buffer;
  209. return logpath;
  210. }
  211. std::string ClassLogFile::GetCurrentFileName()
  212. {
  213. time_t rawtime;
  214. struct tm* timeinfo;
  215. char buffer[60];
  216. time(&rawtime);
  217. timeinfo = localtime(&rawtime);
  218. strftime(buffer, 60, logfile.c_str(), timeinfo);
  219. std::string logpath = logroot + "/" + buffer;
  220. return logpath;
  221. }
  222. void ClassLogFile::RemoveOldLogFile()
  223. {
  224. if (logFileRetentionInDays == 0) {
  225. return;
  226. }
  227. ESP_LOGD(TAG, "Remove old log files");
  228. time_t rawtime;
  229. struct tm* timeinfo;
  230. char cmpfilename[30];
  231. time(&rawtime);
  232. rawtime = addDays(rawtime, -logFileRetentionInDays + 1);
  233. timeinfo = localtime(&rawtime);
  234. //ESP_LOGD(TAG, "logFileRetentionInDays: %d", logFileRetentionInDays);
  235. strftime(cmpfilename, 30, logfile.c_str(), timeinfo);
  236. //ESP_LOGD(TAG, "log file name to compare: %s", cmpfilename);
  237. DIR *dir = opendir(logroot.c_str());
  238. if (!dir) {
  239. ESP_LOGE(TAG, "Failed to stat dir: %s", logroot.c_str());
  240. return;
  241. }
  242. struct dirent *entry;
  243. int deleted = 0;
  244. int notDeleted = 0;
  245. while ((entry = readdir(dir)) != NULL) {
  246. if (entry->d_type == DT_REG) {
  247. //ESP_LOGD(TAG, "compare log file: %s to %s", entry->d_name, cmpfilename);
  248. if ((strlen(entry->d_name) == strlen(cmpfilename)) && (strcmp(entry->d_name, cmpfilename) < 0)) {
  249. //ESP_LOGD(TAG, "delete log file: %s", entry->d_name);
  250. std::string filepath = logroot + "/" + entry->d_name;
  251. if ((strcmp(entry->d_name, "log_1970-01-01.txt") == 0) && getTimeWasNotSetAtBoot()) { // keep logfile log_1970-01-01.txt if time was not set at boot (some boot logs are in there)
  252. //ESP_LOGD(TAG, "Skip deleting this file: %s", entry->d_name);
  253. notDeleted++;
  254. }
  255. else {
  256. if (unlink(filepath.c_str()) == 0) {
  257. deleted++;
  258. }
  259. else {
  260. ESP_LOGE(TAG, "can't delete file: %s", entry->d_name);
  261. notDeleted++;
  262. }
  263. }
  264. }
  265. else {
  266. notDeleted++;
  267. }
  268. }
  269. }
  270. ESP_LOGD(TAG, "log files deleted: %d | files not deleted (incl. leer.txt): %d", deleted, notDeleted);
  271. closedir(dir);
  272. }
  273. void ClassLogFile::RemoveOldDataLog()
  274. {
  275. if (dataLogRetentionInDays == 0 || !doDataLogToSD) {
  276. return;
  277. }
  278. ESP_LOGD(TAG, "Remove old data files");
  279. time_t rawtime;
  280. struct tm* timeinfo;
  281. char cmpfilename[30];
  282. time(&rawtime);
  283. rawtime = addDays(rawtime, -dataLogRetentionInDays + 1);
  284. timeinfo = localtime(&rawtime);
  285. //ESP_LOGD(TAG, "dataLogRetentionInDays: %d", dataLogRetentionInDays);
  286. strftime(cmpfilename, 30, datafile.c_str(), timeinfo);
  287. //ESP_LOGD(TAG, "data file name to compare: %s", cmpfilename);
  288. DIR *dir = opendir(dataroot.c_str());
  289. if (!dir) {
  290. ESP_LOGE(TAG, "Failed to stat dir: %s", dataroot.c_str());
  291. return;
  292. }
  293. struct dirent *entry;
  294. int deleted = 0;
  295. int notDeleted = 0;
  296. while ((entry = readdir(dir)) != NULL) {
  297. if (entry->d_type == DT_REG) {
  298. //ESP_LOGD(TAG, "Compare data file: %s to %s", entry->d_name, cmpfilename);
  299. if ((strlen(entry->d_name) == strlen(cmpfilename)) && (strcmp(entry->d_name, cmpfilename) < 0)) {
  300. //ESP_LOGD(TAG, "delete data file: %s", entry->d_name);
  301. std::string filepath = dataroot + "/" + entry->d_name;
  302. if (unlink(filepath.c_str()) == 0) {
  303. deleted ++;
  304. } else {
  305. ESP_LOGE(TAG, "can't delete file: %s", entry->d_name);
  306. notDeleted ++;
  307. }
  308. } else {
  309. notDeleted ++;
  310. }
  311. }
  312. }
  313. ESP_LOGD(TAG, "data files deleted: %d | files not deleted (incl. leer.txt): %d", deleted, notDeleted);
  314. closedir(dir);
  315. }
  316. bool ClassLogFile::CreateLogDirectories()
  317. {
  318. bool bRetval = false;
  319. bRetval = MakeDir("/sdcard/log");
  320. bRetval = MakeDir("/sdcard/log/data");
  321. bRetval = MakeDir("/sdcard/log/analog");
  322. bRetval = MakeDir("/sdcard/log/digit");
  323. bRetval = MakeDir("/sdcard/log/message");
  324. bRetval = MakeDir("/sdcard/log/source");
  325. return bRetval;
  326. }
  327. ClassLogFile::ClassLogFile(std::string _logroot, std::string _logfile, std::string _logdatapath, std::string _datafile)
  328. {
  329. logroot = _logroot;
  330. logfile = _logfile;
  331. datafile = _datafile;
  332. dataroot = _logdatapath;
  333. logFileRetentionInDays = 3;
  334. dataLogRetentionInDays = 3;
  335. doDataLogToSD = true;
  336. loglevel = ESP_LOG_INFO;
  337. }