19
19
#include " InteractiveCommands.h"
20
20
21
21
#include < platform/logging/LogV.h>
22
+ #include < system/SystemClock.h>
22
23
23
24
#include < editline.h>
24
25
26
+ #include < stdarg.h>
27
+ #include < stdio.h>
25
28
#include < string>
26
29
#include < vector>
27
30
@@ -31,16 +34,52 @@ constexpr char kInteractiveModeStopCommand[] = "quit()";
31
34
32
35
namespace {
33
36
37
+ // File pointer for the log file
38
+ FILE * sLogFile = nullptr ;
39
+
40
+ void OpenLogFile (const char * filePath)
41
+ {
42
+ sLogFile = fopen (filePath, " a" );
43
+ if (sLogFile == nullptr )
44
+ {
45
+ perror (" Failed to open log file" );
46
+ }
47
+ }
48
+
49
+ void CloseLogFile ()
50
+ {
51
+ if (sLogFile != nullptr )
52
+ {
53
+ fclose (sLogFile );
54
+ sLogFile = nullptr ;
55
+ }
56
+ }
57
+
34
58
void ClearLine ()
35
59
{
36
60
printf (" \r\x1B [0J" ); // Move cursor to the beginning of the line and clear from cursor to end of the screen
37
61
}
38
62
39
63
void ENFORCE_FORMAT (3 , 0 ) LoggingCallback(const char * module, uint8_t category, const char * msg, va_list args)
40
64
{
41
- ClearLine ();
42
- chip::Logging::Platform::LogV (module, category, msg, args);
43
- ClearLine ();
65
+ if (sLogFile == nullptr )
66
+ {
67
+ return ;
68
+ }
69
+
70
+ uint64_t timeMs = chip::System::SystemClock ().GetMonotonicMilliseconds64 ().count ();
71
+ uint64_t seconds = timeMs / 1000 ;
72
+ uint64_t milliseconds = timeMs % 1000 ;
73
+
74
+ flockfile (sLogFile );
75
+
76
+ fprintf (sLogFile , " [%llu.%06llu] CHIP:%s: " , static_cast <unsigned long long >(seconds),
77
+ static_cast <unsigned long long >(milliseconds), module);
78
+ vfprintf (sLogFile , msg, args);
79
+ fprintf (sLogFile , " \n " );
80
+ fflush (sLogFile );
81
+
82
+ funlockfile (sLogFile );
44
83
}
45
84
46
85
} // namespace
@@ -90,9 +129,13 @@ CHIP_ERROR InteractiveStartCommand::RunCommand()
90
129
{
91
130
read_history (GetHistoryFilePath ().c_str ());
92
131
93
- // Logs needs to be redirected in order to refresh the screen appropriately when something
94
- // is dumped to stdout while the user is typing a command.
95
- chip::Logging::SetLogRedirectCallback (LoggingCallback);
132
+ if (mLogFilePath .HasValue ())
133
+ {
134
+ OpenLogFile (mLogFilePath .Value ());
135
+
136
+ // Redirect logs to the custom logging callback
137
+ chip::Logging::SetLogRedirectCallback (LoggingCallback);
138
+ }
96
139
97
140
char * command = nullptr ;
98
141
int status;
@@ -112,6 +155,8 @@ CHIP_ERROR InteractiveStartCommand::RunCommand()
112
155
}
113
156
114
157
SetCommandExitStatus (CHIP_NO_ERROR);
158
+ CloseLogFile ();
159
+
115
160
return CHIP_NO_ERROR;
116
161
}
117
162
0 commit comments