diff --git a/src/platform/Linux/Logging.cpp b/src/platform/Linux/Logging.cpp index 28a19a6a30ca28..d9a972848b3fe5 100644 --- a/src/platform/Linux/Logging.cpp +++ b/src/platform/Linux/Logging.cpp @@ -32,6 +32,27 @@ void __attribute__((weak)) OnLogOutput() {} namespace Logging { namespace Platform { +// File pointer for the log file +FILE * logFile = nullptr; + +void OpenLogFile(const char * filePath) +{ + logFile = fopen(filePath, "a"); + if (logFile == nullptr) + { + perror("Failed to open log file"); + } +} + +void CloseLogFile() +{ + if (logFile != nullptr) + { + fclose(logFile); + logFile = nullptr; + } +} + /** * CHIP log output functions. */ @@ -44,17 +65,19 @@ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char gettimeofday(&tv, nullptr); #if !CHIP_USE_PW_LOGGING - // Lock standard output, so a single log line will not be corrupted in case + FILE * outputStream = (logFile == nullptr) ? stdout : logFile; + // Lock outputStream, so a single log line will not be corrupted in case // where multiple threads are using logging subsystem at the same time. - flockfile(stdout); + flockfile(outputStream); - printf("[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), static_cast(tv.tv_usec), - static_cast(syscall(SYS_getpid)), static_cast(syscall(SYS_gettid)), module); - vprintf(msg, v); - printf("\n"); - fflush(stdout); + fprintf(outputStream, "[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), + static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), + static_cast(syscall(SYS_gettid)), module); + vfprintf(outputStream, msg, v); + fprintf(outputStream, "\n"); - funlockfile(stdout); + fflush(outputStream); + funlockfile(outputStream); #else // !CHIP_USE_PW_LOGGING char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; snprintf(formattedMsg, sizeof(formattedMsg), diff --git a/src/platform/logging/LogV.h b/src/platform/logging/LogV.h index 5bff38f284969b..919c0d307be5b3 100644 --- a/src/platform/logging/LogV.h +++ b/src/platform/logging/LogV.h @@ -30,6 +30,25 @@ namespace Platform { */ void ENFORCE_FORMAT(3, 0) LogV(const char * module, uint8_t category, const char * msg, va_list v); +/** + * Open a log file for appending log messages. This function opens + * the specified file and ensures that subsequent logs are written to + * this file. It should be called at the start of the application + * before any logging is done. + * + * @param[in] filePath The path to the log file. If the file does not + * exist, it will be created. If it exists, log + * messages will be appended to it. + */ +void OpenLogFile(const char * filePath); + +/** + * Close the log file if it is open. This function should be called + * at the end of the application to ensure that all log messages are + * flushed to disk and the file is properly closed. + */ +void CloseLogFile(); + } // namespace Platform } // namespace Logging } // namespace chip