127 lines
2.5 KiB
Go
127 lines
2.5 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/charmbracelet/lipgloss"
|
|
"github.com/spf13/cobra"
|
|
|
|
"gitlab.com/ghaymah/gy/internal/apiclient"
|
|
"gitlab.com/ghaymah/gy/internal/uit"
|
|
)
|
|
|
|
func newLogsCmd() *cobra.Command {
|
|
var name string
|
|
var follow bool
|
|
var max int
|
|
cmd := &cobra.Command{
|
|
Use: "logs",
|
|
Short: "Show an app's logs",
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
c, err := requireClient()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
app, err := resolveApp(c, cwd(), name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return streamLogs(c, app.ID, follow, max)
|
|
},
|
|
}
|
|
cmd.Flags().StringVar(&name, "name", "", "app name (defaults to the linked app)")
|
|
cmd.Flags().BoolVarP(&follow, "follow", "f", false, "follow the log stream")
|
|
cmd.Flags().IntVar(&max, "max", 200, "max lines to fetch")
|
|
return cmd
|
|
}
|
|
|
|
func streamLogs(c *apiclient.Client, appID string, follow bool, max int) error {
|
|
if max <= 0 {
|
|
max = 200
|
|
}
|
|
|
|
seen := make(map[string]bool)
|
|
printNew := func(logs []apiclient.LogEntry) {
|
|
// Cumin returns logs newest-first; print them oldest-first.
|
|
for i := len(logs) - 1; i >= 0; i-- {
|
|
l := logs[i]
|
|
key := l.Timestamp + "\x00" + l.Message
|
|
if seen[key] {
|
|
continue
|
|
}
|
|
seen[key] = true
|
|
fmt.Println(renderLogLine(l))
|
|
}
|
|
}
|
|
|
|
// Keep the seen set bounded for long-running follows.
|
|
trimSeen := func() {
|
|
if len(seen) > 2000 {
|
|
for k := range seen {
|
|
delete(seen, k)
|
|
if len(seen) <= 1000 {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
stop := make(chan os.Signal, 1)
|
|
if follow {
|
|
signal.Notify(stop, os.Interrupt)
|
|
defer signal.Stop(stop)
|
|
}
|
|
|
|
for {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
logs, err := c.AppLogs(ctx, appID, max)
|
|
cancel()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
printNew(logs)
|
|
trimSeen()
|
|
|
|
if !follow {
|
|
return nil
|
|
}
|
|
select {
|
|
case <-stop:
|
|
return nil
|
|
case <-time.After(2 * time.Second):
|
|
}
|
|
}
|
|
}
|
|
|
|
func renderLogLine(l apiclient.LogEntry) string {
|
|
line := strings.TrimSpace(stripANSI(l.Message))
|
|
if line == "" {
|
|
return ""
|
|
}
|
|
var prefix string
|
|
switch l.Severity {
|
|
case "error", "fatal":
|
|
prefix = uit.Err.Render("✗")
|
|
case "warn", "warning":
|
|
prefix = uit.Warn.Render("!")
|
|
default:
|
|
prefix = uit.Dim.Render("·")
|
|
}
|
|
ts := ""
|
|
if l.Timestamp != "" {
|
|
t, err := time.Parse(time.RFC3339, l.Timestamp)
|
|
if err == nil {
|
|
ts = t.Local().Format("15:04:05")
|
|
}
|
|
}
|
|
if ts != "" {
|
|
ts = uit.Dim.Render(ts) + " "
|
|
}
|
|
return lipgloss.JoinHorizontal(lipgloss.Left, prefix+" ", ts, line)
|
|
}
|