1
1
package cmd
2
2
3
3
import (
4
+ "bufio"
5
+ "fmt"
6
+ "io"
7
+ "os"
8
+ "os/signal"
9
+ "path/filepath"
10
+ "syscall"
11
+ "time"
12
+
4
13
tea "github.com/charmbracelet/bubbletea"
5
14
"github.com/spf13/cobra"
6
15
@@ -9,6 +18,10 @@ import (
9
18
"github.com/initia-labs/weave/utils"
10
19
)
11
20
21
+ const (
22
+ PreviousLogLines = 100
23
+ )
24
+
12
25
func InitiaCommand () * cobra.Command {
13
26
cmd := & cobra.Command {
14
27
Use : "initia" ,
@@ -87,11 +100,70 @@ func initiaLogCommand() *cobra.Command {
87
100
Use : "log" ,
88
101
Short : "Stream the logs of the initiad full node application." ,
89
102
RunE : func (cmd * cobra.Command , args []string ) error {
90
- // TODO: Implement log streaming
103
+ userHome , err := os .UserHomeDir ()
104
+ if err != nil {
105
+ return fmt .Errorf ("failed to get user home directory: %v" , err )
106
+ }
107
+
108
+ logFilePathOut := filepath .Join (userHome , utils .WeaveLogDirectory , "initia.stdout.log" )
109
+ logFilePathErr := filepath .Join (userHome , utils .WeaveLogDirectory , "initia.stderr.log" )
91
110
111
+ sigChan := make (chan os.Signal , 1 )
112
+ signal .Notify (sigChan , os .Interrupt , syscall .SIGTERM )
113
+
114
+ go tailLogFile (logFilePathOut , os .Stdout )
115
+ go tailLogFile (logFilePathErr , os .Stderr )
116
+
117
+ <- sigChan
118
+
119
+ fmt .Println ("Stopping log streaming..." )
92
120
return nil
93
121
},
94
122
}
95
123
96
124
return logCmd
97
125
}
126
+
127
+ func tailLogFile (filePath string , output io.Writer ) {
128
+ file , err := os .Open (filePath )
129
+ if err != nil {
130
+ fmt .Printf ("error opening log file %s: %v\n " , filePath , err )
131
+ return
132
+ }
133
+ defer file .Close ()
134
+
135
+ var lines []string
136
+ scanner := bufio .NewScanner (file )
137
+
138
+ for scanner .Scan () {
139
+ lines = append (lines , scanner .Text ())
140
+ if len (lines ) > PreviousLogLines {
141
+ lines = lines [1 :]
142
+ }
143
+ }
144
+
145
+ for _ , line := range lines {
146
+ fmt .Fprintln (output , line )
147
+ }
148
+
149
+ _ , err = file .Seek (0 , io .SeekEnd )
150
+ if err != nil {
151
+ fmt .Printf ("error seeking to end of log file %s: %v\n " , filePath , err )
152
+ return
153
+ }
154
+
155
+ for {
156
+ var line = make ([]byte , 4096 )
157
+ n , err := file .Read (line )
158
+ if err != nil && err != io .EOF {
159
+ fmt .Printf ("error reading log file %s: %v\n " , filePath , err )
160
+ return
161
+ }
162
+
163
+ if n > 0 {
164
+ output .Write (line [:n ])
165
+ } else {
166
+ time .Sleep (1 * time .Second )
167
+ }
168
+ }
169
+ }
0 commit comments