Skip to content

Commit 6f1a307

Browse files
committed
feat: log jounalctl
1 parent 4d93853 commit 6f1a307

File tree

1 file changed

+45
-14
lines changed

1 file changed

+45
-14
lines changed

cmd/initia.go

+45-14
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ import (
55
"fmt"
66
"io"
77
"os"
8+
"os/exec"
89
"os/signal"
910
"path/filepath"
11+
"runtime"
1012
"syscall"
1113
"time"
1214

@@ -107,28 +109,57 @@ func initiaLogCommand() *cobra.Command {
107109
Use: "log",
108110
Short: "Stream the logs of the initiad full node application.",
109111
RunE: func(cmd *cobra.Command, args []string) error {
110-
userHome, err := os.UserHomeDir()
111-
if err != nil {
112-
return fmt.Errorf("failed to get user home directory: %v", err)
112+
// Check if the OS is Linux
113+
switch runtime.GOOS {
114+
case "linux":
115+
return streamLogsFromJournalctl()
116+
case "darwin":
117+
// If not Linux, fall back to file-based log streaming
118+
return streamLogsFromFiles()
119+
default:
120+
return fmt.Errorf("unsupported OS: %s", runtime.GOOS)
113121
}
122+
},
123+
}
114124

115-
logFilePathOut := filepath.Join(userHome, utils.WeaveLogDirectory, "initia.stdout.log")
116-
logFilePathErr := filepath.Join(userHome, utils.WeaveLogDirectory, "initia.stderr.log")
125+
return logCmd
126+
}
117127

118-
sigChan := make(chan os.Signal, 1)
119-
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
128+
// streamLogsFromJournalctl uses journalctl to stream logs from initia.service
129+
func streamLogsFromJournalctl() error {
130+
// Execute the journalctl command to follow logs of initia.service
131+
cmd := exec.Command("journalctl", "-f", "-u", "initia.service")
132+
cmd.Stdout = os.Stdout
133+
cmd.Stderr = os.Stderr
120134

121-
go tailLogFile(logFilePathOut, os.Stdout)
122-
go tailLogFile(logFilePathErr, os.Stderr)
135+
// Run the command and return any errors
136+
if err := cmd.Run(); err != nil {
137+
return fmt.Errorf("failed to stream logs using journalctl: %v", err)
138+
}
123139

124-
<-sigChan
140+
return nil
141+
}
125142

126-
fmt.Println("Stopping log streaming...")
127-
return nil
128-
},
143+
// streamLogsFromFiles streams logs from file-based logs
144+
func streamLogsFromFiles() error {
145+
userHome, err := os.UserHomeDir()
146+
if err != nil {
147+
return fmt.Errorf("failed to get user home directory: %v", err)
129148
}
130149

131-
return logCmd
150+
logFilePathOut := filepath.Join(userHome, utils.WeaveLogDirectory, "initia.stdout.log")
151+
logFilePathErr := filepath.Join(userHome, utils.WeaveLogDirectory, "initia.stderr.log")
152+
153+
sigChan := make(chan os.Signal, 1)
154+
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
155+
156+
go tailLogFile(logFilePathOut, os.Stdout)
157+
go tailLogFile(logFilePathErr, os.Stderr)
158+
159+
<-sigChan
160+
161+
fmt.Println("Stopping log streaming...")
162+
return nil
132163
}
133164

134165
func tailLogFile(filePath string, output io.Writer) {

0 commit comments

Comments
 (0)