-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
main.go
185 lines (147 loc) · 6.14 KB
/
main.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
package main
import (
"log"
"net/url"
"os"
"time"
_ "github.com/grafana/loki/pkg/build"
"github.com/grafana/loki/pkg/logcli/client"
"github.com/grafana/loki/pkg/logcli/labelquery"
"github.com/grafana/loki/pkg/logcli/output"
"github.com/grafana/loki/pkg/logcli/query"
"github.com/prometheus/common/config"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
app = kingpin.New("logcli", "A command-line for loki.").Version(version.Print("logcli"))
quiet = app.Flag("quiet", "suppress everything but log lines").Default("false").Short('q').Bool()
outputMode = app.Flag("output", "specify output mode [default, raw, jsonl]").Default("default").Short('o').Enum("default", "raw", "jsonl")
timezone = app.Flag("timezone", "Specify the timezone to use when formatting output timestamps [Local, UTC]").Default("Local").Short('z').Enum("Local", "UTC")
queryClient = newQueryClient(app)
queryCmd = app.Command("query", "Run a LogQL query.")
rangeQuery = newQuery(false, queryCmd)
tail = queryCmd.Flag("tail", "Tail the logs").Short('t').Default("false").Bool()
delayFor = queryCmd.Flag("delay-for", "Delay in tailing by number of seconds to accumulate logs for re-ordering").Default("0").Int()
instantQueryCmd = app.Command("instant-query", "Run an instant LogQL query")
instantQuery = newQuery(true, instantQueryCmd)
labelsCmd = app.Command("labels", "Find values for a given label.")
labelName = labelsCmd.Arg("label", "The name of the label.").HintAction(hintActionLabelNames).String()
)
func main() {
log.SetOutput(os.Stderr)
cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
switch cmd {
case queryCmd.FullCommand():
location, err := time.LoadLocation(*timezone)
if err != nil {
log.Fatalf("Unable to load timezone '%s': %s", *timezone, err)
}
outputOptions := &output.LogOutputOptions{
Timezone: location,
NoLabels: rangeQuery.NoLabels,
}
out, err := output.NewLogOutput(*outputMode, outputOptions)
if err != nil {
log.Fatalf("Unable to create log output: %s", err)
}
if *tail {
rangeQuery.TailQuery(*delayFor, queryClient, out)
} else {
rangeQuery.DoQuery(queryClient, out)
}
case instantQueryCmd.FullCommand():
location, err := time.LoadLocation(*timezone)
if err != nil {
log.Fatalf("Unable to load timezone '%s': %s", *timezone, err)
}
outputOptions := &output.LogOutputOptions{
Timezone: location,
NoLabels: instantQuery.NoLabels,
}
out, err := output.NewLogOutput(*outputMode, outputOptions)
if err != nil {
log.Fatalf("Unable to create log output: %s", err)
}
instantQuery.DoQuery(queryClient, out)
case labelsCmd.FullCommand():
q := newLabelQuery(*labelName, *quiet)
q.DoLabels(queryClient)
}
}
func hintActionLabelNames() []string {
q := newLabelQuery("", *quiet)
return q.ListLabels(queryClient)
}
func newQueryClient(app *kingpin.Application) *client.Client {
client := &client.Client{
TLSConfig: config.TLSConfig{},
}
// extract host
addressAction := func(c *kingpin.ParseContext) error {
u, err := url.Parse(client.Address)
if err != nil {
return err
}
client.TLSConfig.ServerName = u.Host
return nil
}
app.Flag("addr", "Server address.").Default("https://logs-us-west1.grafana.net").Envar("GRAFANA_ADDR").Action(addressAction).StringVar(&client.Address)
app.Flag("username", "Username for HTTP basic auth.").Default("").Envar("GRAFANA_USERNAME").StringVar(&client.Username)
app.Flag("password", "Password for HTTP basic auth.").Default("").Envar("GRAFANA_PASSWORD").StringVar(&client.Password)
app.Flag("ca-cert", "Path to the server Certificate Authority.").Default("").Envar("LOKI_CA_CERT_PATH").StringVar(&client.TLSConfig.CAFile)
app.Flag("tls-skip-verify", "Server certificate TLS skip verify.").Default("false").BoolVar(&client.TLSConfig.InsecureSkipVerify)
app.Flag("cert", "Path to the client certificate.").Default("").Envar("LOKI_CLIENT_CERT_PATH").StringVar(&client.TLSConfig.CertFile)
app.Flag("key", "Path to the client certificate key.").Default("").Envar("LOKI_CLIENT_KEY_PATH").StringVar(&client.TLSConfig.KeyFile)
return client
}
func newLabelQuery(labelName string, quiet bool) *labelquery.LabelQuery {
return &labelquery.LabelQuery{
LabelName: labelName,
Quiet: quiet,
}
}
func newQuery(instant bool, cmd *kingpin.CmdClause) *query.Query {
// calculcate query range from cli params
var now, from, to string
var since time.Duration
query := &query.Query{}
// executed after all command flags are parsed
cmd.Action(func(c *kingpin.ParseContext) error {
if instant {
query.SetInstant(mustParse(now, time.Now()))
} else {
defaultEnd := time.Now()
defaultStart := defaultEnd.Add(-since)
query.Start = mustParse(from, defaultStart)
query.End = mustParse(to, defaultEnd)
}
return nil
})
cmd.Arg("query", "eg '{foo=\"bar\",baz=~\".*blip\"} |~ \".*error.*\"'").Required().StringVar(&query.QueryString)
cmd.Flag("limit", "Limit on number of entries to print.").Default("30").IntVar(&query.Limit)
if instant {
cmd.Flag("now", "Time at which to execute the instant query.").StringVar(&now)
} else {
cmd.Flag("since", "Lookback window.").Default("1h").DurationVar(&since)
cmd.Flag("from", "Start looking for logs at this absolute time (inclusive)").StringVar(&from)
cmd.Flag("to", "Stop looking for logs at this absolute time (exclusive)").StringVar(&to)
cmd.Flag("step", "Query resolution step width").DurationVar(&query.Step)
}
cmd.Flag("forward", "Scan forwards through logs.").Default("false").BoolVar(&query.Forward)
cmd.Flag("no-labels", "Do not print any labels").Default("false").BoolVar(&query.NoLabels)
cmd.Flag("exclude-label", "Exclude labels given the provided key during output.").StringsVar(&query.IgnoreLabelsKey)
cmd.Flag("include-label", "Include labels given the provided key during output.").StringsVar(&query.ShowLabelsKey)
cmd.Flag("labels-length", "Set a fixed padding to labels").Default("0").IntVar(&query.FixedLabelsLen)
return query
}
func mustParse(t string, defaultTime time.Time) time.Time {
if t == "" {
return defaultTime
}
ret, err := time.Parse(time.RFC3339Nano, t)
if err != nil {
log.Fatalf("Unable to parse time %v", err)
}
return ret
}