Skip to content

Commit

Permalink
Redirect the log to log file from console (#36257)
Browse files Browse the repository at this point in the history
  • Loading branch information
yufengwangca authored and lboue committed Nov 28, 2024
1 parent b3598e9 commit 1057656
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions examples/fabric-sync/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<unsigned long long>(seconds),
static_cast<unsigned long long>(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[])
Expand Down

0 comments on commit 1057656

Please sign in to comment.