ClassLogFile.cpp 12 KB

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