fix: hook the log lock into log_printfv

The Arduino core already links with --wrap=log_printf for the ESP
Insights hook in libesp_diagnostics, so defining __wrap_log_printf
failed to link with a duplicate definition. That hook prints through
log_printfv, so wrap that instead and take the lock there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cjkas 2026-10-11 22:23:11 +02:00
parent 0610dc4369
commit b6ed24f5bb
2 changed files with 11 additions and 12 deletions

View file

@ -1,20 +1,21 @@
// Prints each log line whole.
//
// The Arduino core's log_printf() writes with ets_printf() and has its UART
// The Arduino core's log_printfv() writes with ets_printf() and has its UART
// lock commented out, so lines logged at the same time from async_tcp (core 0)
// and loop() (core 1) come out interleaved character by character. It also
// formats short lines into one static buffer shared by every task.
//
// platformio.ini links with -Wl,--wrap=log_printf so every ESP_LOGx/log_x call
// lands here and takes this lock around the core's log_printfv().
// The core already links with --wrap=log_printf, which sends every
// ESP_LOGx/log_x call to the ESP Insights hook in libesp_diagnostics, and that
// hook prints through log_printfv(). platformio.ini adds
// -Wl,--wrap=log_printfv so that call lands here and takes this lock.
#include <Arduino.h>
#include <stdarg.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
// Defined in the core's esp32-hal-uart.c but not declared in a header.
extern "C" int log_printfv(const char *format, va_list arg);
extern "C" int __real_log_printfv(const char *format, va_list arg);
// Created during static initialisation, before anything can race for it. A
// constructor that logs before this runs simply goes unlocked.
@ -23,14 +24,11 @@ static SemaphoreHandle_t logMutex = xSemaphoreCreateRecursiveMutex();
// task stuck mid-log can only garble output, not hang another task.
#define LOG_LOCK_WAIT_MS 50
extern "C" int __wrap_log_printf(const char *format, ...) {
extern "C" int __wrap_log_printfv(const char *format, va_list arg) {
// No blocking before the scheduler runs, in an ISR or in a critical section.
const bool canLock = logMutex && xTaskGetSchedulerState() == taskSCHEDULER_RUNNING && xPortCanYield();
const bool locked = canLock && xSemaphoreTakeRecursive(logMutex, pdMS_TO_TICKS(LOG_LOCK_WAIT_MS)) == pdTRUE;
va_list arg;
va_start(arg, format);
int len = log_printfv(format, arg);
va_end(arg);
int len = __real_log_printfv(format, arg);
if(locked) xSemaphoreGiveRecursive(logMutex);
return len;
}