Skip to content

Commit 5669563

Browse files
committed
feat: weave initia log
1 parent df5dd82 commit 5669563

File tree

1 file changed

+73
-1
lines changed

1 file changed

+73
-1
lines changed

cmd/initia.go

+73-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
package cmd
22

33
import (
4+
"bufio"
5+
"fmt"
6+
"io"
7+
"os"
8+
"os/signal"
9+
"path/filepath"
10+
"syscall"
11+
"time"
12+
413
tea "github.com/charmbracelet/bubbletea"
514
"github.com/spf13/cobra"
615

@@ -9,6 +18,10 @@ import (
918
"github.com/initia-labs/weave/utils"
1019
)
1120

21+
const (
22+
PreviousLogLines = 100
23+
)
24+
1225
func InitiaCommand() *cobra.Command {
1326
cmd := &cobra.Command{
1427
Use: "initia",
@@ -87,11 +100,70 @@ func initiaLogCommand() *cobra.Command {
87100
Use: "log",
88101
Short: "Stream the logs of the initiad full node application.",
89102
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")
91110

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...")
92120
return nil
93121
},
94122
}
95123

96124
return logCmd
97125
}
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

Comments
 (0)