Răsfoiți Sursa

fix(log): don't share the log FILE handle between tasks

With KEEP_LOGFILE_OPEN_FOR_APPENDING off (the default), WriteToFile()
opened the day's log file into the member logFileAppendHandle, wrote
the line and closed it again. WriteToFile() runs in several tasks (flow,
HTTP server, MQTT, Wi-Fi events) without a lock. When two of them log at
the same time, one overwrites or closes the other's handle:

- the overwritten FILE is never closed. The SD card is mounted with
  max_files = 12, so every leak takes one of the few handles, and once
  they are gone every fopen() fails (config, images, logs).
- the other task calls fputs()/fclose() on a handle that is already
  closed or NULL, which corrupts the heap or panics.

The default branch now uses a local FILE* per call. The KEEP_ branch
is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Victor Gladkikh 1 lună în urmă
părinte
comite
c1c2b75623
1 a modificat fișierele cu 11 adăugiri și 11 ștergeri
  1. 11 11
      code/components/jomjol_logfile/ClassLogFile.cpp

+ 11 - 11
code/components/jomjol_logfile/ClassLogFile.cpp

@@ -221,22 +221,22 @@ void ClassLogFile::WriteToFile(esp_log_level_t level, std::string tag, std::stri
 
         fileNameDate = fileNameDateNew;
     }
-#else
-    std::string logpath = logroot + "/" + fileNameDateNew; 
-    logFileAppendHandle = fopen(logpath.c_str(), "a+");
-    if (logFileAppendHandle==NULL) {
-        ESP_LOGE(TAG, "Can't open log file %s", logpath.c_str());
-        return;
-    }
-  #endif
 
     fputs(fullmessage.c_str(), logFileAppendHandle);
-    
-#ifdef KEEP_LOGFILE_OPEN_FOR_APPENDING
     fflush(logFileAppendHandle);
     fsync(fileno(logFileAppendHandle));
 #else
-    CloseLogFileAppendHandle();
+    // Local handle: WriteToFile is called from several tasks, a shared member handle
+    // could be overwritten/closed by another task (FILE leak, fputs on NULL)
+    std::string logpath = logroot + "/" + fileNameDateNew;
+    FILE* pLogFile = fopen(logpath.c_str(), "a+");
+    if (pLogFile==NULL) {
+        ESP_LOGE(TAG, "Can't open log file %s", logpath.c_str());
+        return;
+    }
+
+    fputs(fullmessage.c_str(), pLogFile);
+    fclose(pLogFile);
 #endif
 }