@@ -118,9 +118,7 @@ int esp_log_router_flash_vprintf(const char *format, va_list args)
118118 }
119119
120120 // Lock mutex for thread safety
121- if (g_log_router_mutex ) {
122- xSemaphoreTake (g_log_router_mutex , pdMS_TO_TICKS (100 ));
123- }
121+ xSemaphoreTake (g_log_router_mutex , portMAX_DELAY );
124122
125123 // Write to all files that match the log level
126124 esp_log_router_slist_t * item ;
@@ -244,9 +242,7 @@ int esp_log_router_flash_vprintf(const char *format, va_list args)
244242 }
245243
246244 // Release mutex
247- if (g_log_router_mutex ) {
248- xSemaphoreGive (g_log_router_mutex );
249- }
245+ xSemaphoreGive (g_log_router_mutex );
250246
251247 return ret ;
252248}
@@ -290,6 +286,15 @@ static void esp_log_router_shutdown(void)
290286
291287esp_err_t esp_log_router_to_file (const char * file_path , const char * tag , esp_log_level_t level )
292288{
289+ // Create mutex for thread safety, the first time this function is called.
290+ if (g_log_router_mutex == NULL ) {
291+ g_log_router_mutex = xSemaphoreCreateMutex ();
292+ if (g_log_router_mutex == NULL ) {
293+ ESP_LOGE (TAG , "Failed to create mutex for log router" );
294+ return ESP_ERR_NO_MEM ;
295+ }
296+ }
297+
293298 if (!file_path ) {
294299 return ESP_ERR_INVALID_ARG ;
295300 }
@@ -376,12 +381,6 @@ esp_err_t esp_log_router_to_file(const char* file_path, const char* tag, esp_log
376381 SLIST_INSERT_HEAD (& g_esp_log_router_slist_head , new_log_router , next );
377382 g_esp_log_router_vprintf = esp_log_set_vprintf (esp_log_router_flash_vprintf );
378383 esp_register_shutdown_handler (esp_log_router_shutdown );
379-
380- // Create mutex for thread safety when first node is added
381- g_log_router_mutex = xSemaphoreCreateMutex ();
382- if (g_log_router_mutex == NULL ) {
383- ESP_LOGW (TAG , "Failed to create mutex for log router" );
384- }
385384 } else {
386385 // Find the last node and insert after it
387386 esp_log_router_slist_t * last = SLIST_FIRST (& g_esp_log_router_slist_head );
0 commit comments