From 87396c80a6651bca432619bf3ef710f9b82334a9 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 25 Oct 2024 21:20:23 -0700 Subject: [PATCH] Redirect the log to log file from console --- examples/fabric-sync/main.cpp | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/examples/fabric-sync/main.cpp b/examples/fabric-sync/main.cpp index 84c014dfcbf010..66541b32de91f9 100644 --- a/examples/fabric-sync/main.cpp +++ b/examples/fabric-sync/main.cpp @@ -20,14 +20,69 @@ using namespace chip; +namespace { + +constexpr char kFabricSyncLogFilePath[] = "/tmp/fabric_sync.log"; + +// File pointer for the log file +FILE * sLogFile = nullptr; + +void OpenLogFile(const char * filePath) +{ + sLogFile = fopen(filePath, "a"); + if (sLogFile == nullptr) + { + perror("Failed to open log file"); + } +} + +void CloseLogFile() +{ + if (sLogFile != nullptr) + { + fclose(sLogFile); + sLogFile = nullptr; + } +} + +void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, const char * msg, va_list args) +{ + if (sLogFile == nullptr) + { + return; + } + + uint64_t timeMs = System::SystemClock().GetMonotonicMilliseconds64().count(); + uint64_t seconds = timeMs / 1000; + uint64_t milliseconds = timeMs % 1000; + + flockfile(sLogFile); + + fprintf(sLogFile, "[%llu.%06llu] CHIP:%s: ", static_cast(seconds), + static_cast(milliseconds), module); + vfprintf(sLogFile, msg, args); + fprintf(sLogFile, "\n"); + fflush(sLogFile); + + funlockfile(sLogFile); +} + +} // namespace + void ApplicationInit() { ChipLogProgress(NotSpecified, "Fabric-Sync: ApplicationInit()"); + + OpenLogFile(kFabricSyncLogFilePath); + + // Redirect logs to the custom logging callback + Logging::SetLogRedirectCallback(LoggingCallback); } void ApplicationShutdown() { ChipLogDetail(NotSpecified, "Fabric-Sync: ApplicationShutdown()"); + CloseLogFile(); } int main(int argc, char * argv[])