-
Notifications
You must be signed in to change notification settings - Fork 221
/
logs.go
252 lines (198 loc) · 5.68 KB
/
logs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Package logs implements the logs command chain.
package logs
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"time"
"github.com/logrusorgru/aurora"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/pkg/iostreams"
"github.com/superfly/flyctl/pkg/logs"
"github.com/superfly/flyctl/internal/cli/internal/app"
"github.com/superfly/flyctl/internal/cli/internal/command"
"github.com/superfly/flyctl/internal/cli/internal/config"
"github.com/superfly/flyctl/internal/cli/internal/flag"
"github.com/superfly/flyctl/internal/cli/internal/render"
"github.com/superfly/flyctl/internal/client"
"github.com/superfly/flyctl/internal/logger"
)
func New() (cmd *cobra.Command) {
const (
long = `View application logs as generated by the application running on
the Fly platform.
Logs can be filtered to a specific instance using the --instance/-i flag or
to all instances running in a specific region using the --region/-r flag.
`
short = "View app logs"
)
cmd = command.New("logs", short, long, run,
command.RequireSession,
command.RequireAppName,
)
cmd.Args = cobra.NoArgs
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.Region(),
flag.String{
Name: "instance",
Shorthand: "i",
Description: "Filter by instance ID",
},
)
return
}
func run(ctx context.Context) error {
appName := app.NameFromContext(ctx)
client := client.FromContext(ctx).API()
app, err := client.GetApp(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
opts := &logs.LogOptions{
AppName: app.Name,
RegionCode: config.FromContext(ctx).Region,
VMID: flag.GetString(ctx, "instance"),
}
var eg *errgroup.Group
eg, ctx = errgroup.WithContext(ctx)
pollingCtx, cancelPolling := context.WithCancel(ctx)
pollEntries := poll(pollingCtx, eg, client, opts)
liveEntries := nats(ctx, eg, client, opts, cancelPolling)
eg.Go(func() error {
return printStreams(ctx, pollEntries, liveEntries)
})
return eg.Wait()
}
func poll(ctx context.Context, eg *errgroup.Group, client *api.Client, opts *logs.LogOptions) <-chan logs.LogEntry {
c := make(chan logs.LogEntry)
eg.Go(func() (err error) {
defer close(c)
if err = logs.Poll(ctx, c, client, opts); errors.Is(err, context.Canceled) {
// if the parent context is cancelled then the errorgroup will return
// context.Canceled because nats and/or printStreams will return it.
err = nil
}
return
})
return c
}
func nats(ctx context.Context, eg *errgroup.Group, client *api.Client, opts *logs.LogOptions, cancelPolling context.CancelFunc) <-chan logs.LogEntry {
c := make(chan logs.LogEntry)
eg.Go(func() error {
defer close(c)
stream, err := logs.NewNatsStream(ctx, client, opts)
if err != nil {
logger := logger.FromContext(ctx)
logger.Debugf("could not connect to wireguard tunnel: %v\n", err)
logger.Debug("falling back to log polling...")
return nil
}
cancelPolling()
for entry := range stream.Stream(ctx, opts) {
c <- entry
}
return nil
})
return c
}
func printStreams(ctx context.Context, streams ...<-chan logs.LogEntry) error {
var eg *errgroup.Group
eg, ctx = errgroup.WithContext(ctx)
out := iostreams.FromContext(ctx).Out
json := config.FromContext(ctx).JSONOutput
for _, stream := range streams {
stream := stream
eg.Go(func() error {
return printStream(ctx, out, stream, json)
})
}
return eg.Wait()
}
func printStream(ctx context.Context, w io.Writer, stream <-chan logs.LogEntry, json bool) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case entry, ok := <-stream:
if !ok {
return nil
}
var err error
if json {
err = render.JSON(w, entry)
} else {
err = printEntry(w, entry)
}
if err != nil {
return err
}
}
}
}
func printEntry(w io.Writer, entry logs.LogEntry) (err error) {
var ts time.Time
if ts, err = time.Parse(time.RFC3339Nano, entry.Timestamp); err != nil {
err = fmt.Errorf("failed parsing timestamp %q: %w\n", entry.Timestamp, err)
return
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s ", aurora.Faint(format(ts)))
if entry.Meta.Event.Provider != "" {
if entry.Instance != "" {
fmt.Fprintf(&buf, "%s[%s]", entry.Meta.Event.Provider, entry.Instance)
} else {
fmt.Fprint(&buf, entry.Meta.Event.Provider)
}
} else if entry.Instance != "" {
fmt.Fprintf(&buf, "%s", entry.Instance)
}
fmt.Fprintf(&buf, " %s [%s]", aurora.Green(entry.Region), aurora.Colorize(entry.Level, levelColor(entry.Level)))
printFieldIfPresent(&buf, "error.code", entry.Meta.Error.Code)
hadErrorMsg := printFieldIfPresent(w, "error.message", entry.Meta.Error.Message)
printFieldIfPresent(&buf, "request.method", entry.Meta.HTTP.Request.Method)
printFieldIfPresent(&buf, "request.url", entry.Meta.URL.Full)
printFieldIfPresent(&buf, "request.id", entry.Meta.HTTP.Request.ID)
printFieldIfPresent(&buf, "response.status", entry.Meta.HTTP.Response.StatusCode)
if !hadErrorMsg {
buf.Write([]byte(entry.Message))
}
buf.WriteByte('\n')
_, err = buf.WriteTo(w)
return err
}
func printFieldIfPresent(w io.Writer, name string, value interface{}) (present bool) {
switch v := value.(type) {
case string:
if v != "" {
fmt.Fprintf(w, `%s"%s" `, aurora.Faint(name+"="), v)
present = true
}
case int:
if v > 0 {
fmt.Fprintf(w, "%s%d ", aurora.Faint(name+"="), v)
present = true
}
}
return
}
func levelColor(level string) aurora.Color {
switch level {
default:
return aurora.RedFg
case "debug":
return aurora.CyanFg
case "info":
return aurora.BlueFg
case "warn", "warning":
return aurora.YellowFg
}
}
func format(t time.Time) string {
return t.Format("2006-01-02T15:04:05.000")
}