ClassLogFile.cpp 13 KB

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