Debian Codegraph @

cmd/humanlog/main.go

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "log"
7 "os"
8 "os/signal"
9 "runtime"
10 "strconv"
11 "strings"
12
13 "github.com/aybabtme/rgbterm"
14 "github.com/blang/semver"
15 types "github.com/humanlogio/api/go/types/v1"
16 "github.com/humanlogio/humanlog"
17 "github.com/humanlogio/humanlog/internal/pkg/config"
18 "github.com/humanlogio/humanlog/internal/pkg/state"
•19 "github.com/humanlogio/humanlog/pkg/sink/stdiosink"
20 "github.com/mattn/go-colorable"
21 "github.com/urfave/cli"
22 )
23
24 var (
25 versionMajor = "0"
26 versionMinor = "0"
27 versionPatch = "0"
28 versionPrerelease = "devel"
29 versionBuild = ""
30 version = func() *types.Version {
31 var prerelease []string
32 if versionPrerelease != "" {
33 prerelease = append(prerelease, versionPrerelease)
34 }
35 return &types.Version{
36 Major: int32(mustatoi(versionMajor)),
37 Minor: int32(mustatoi(versionMinor)),
38 Patch: int32(mustatoi(versionPatch)),
39 Prereleases: prerelease,
40 Build: versionBuild,
41 }
42 }()
43 semverVersion = func() semver.Version {
44 v, err := version.AsSemver()
45 if err != nil {
46 panic(err)
47 }
48 return v
49 }()
50 )
51
52 func fatalf(c *cli.Context, format string, args ...interface{}) {
53 log.Printf(format, args...)
54 cli.ShowAppHelp(c)
55 os.Exit(1)
56 }
57
58 func main() {
59 app := newApp()
60
61 prefix := rgbterm.FgString(app.Name+"> ", 99, 99, 99)
62
63 log.SetOutput(colorable.NewColorableStderr())
64 log.SetFlags(0)
65 log.SetPrefix(prefix)
66 err := app.Run(os.Args)
67 if err != nil {
68 log.Fatal(err)
69 }
70 }
71 func newApp() *cli.App {
72
73 configFlag := cli.StringFlag{
74 Name: "config",
75 Usage: "specify a config file to use, otherwise uses the default one",
76 }
77
78 skip := cli.StringSlice{}
79 keep := cli.StringSlice{}
80
81 skipFlag := cli.StringSliceFlag{
82 Name: "skip",
83 Usage: "keys to skip when parsing a log entry",
84 Value: &skip,
85 }
86
87 keepFlag := cli.StringSliceFlag{
88 Name: "keep",
89 Usage: "keys to keep when parsing a log entry",
90 Value: &keep,
91 }
92
93 sortLongest := cli.BoolTFlag{
94 Name: "sort-longest",
95 Usage: "sort by longest key after having sorted lexicographically",
96 }
97
98 skipUnchanged := cli.BoolTFlag{
99 Name: "skip-unchanged",
100 Usage: "skip keys that have the same value than the previous entry",
101 }
102
103 truncates := cli.BoolFlag{
104 Name: "truncate",
105 Usage: "truncates values that are longer than --truncate-length",
106 }
107
108 truncateLength := cli.IntFlag{
109 Name: "truncate-length",
110 Usage: "truncate values that are longer than this length",
111 Value: *config.DefaultConfig.TruncateLength,
112 }
113
114 colorFlag := cli.StringFlag{
115 Name: "color",
116 Usage: "specify color mode: auto, on/force, off",
117 Value: stdiosink.DefaultStdioOpts.ColorFlag,
118 }
119
120 lightBg := cli.BoolFlag{
121 Name: "light-bg",
122 Usage: "use black as the base foreground color (for terminals with light backgrounds)",
123 }
124
125 timeFormat := cli.StringFlag{
126 Name: "time-format",
127 Usage: "output time format, see https://golang.org/pkg/time/ for details",
128 Value: stdiosink.DefaultStdioOpts.TimeFormat,
129 }
130
131 ignoreInterrupts := cli.BoolFlag{
132 Name: "ignore-interrupts, i",
133 Usage: "ignore interrupts",
134 }
135
136 messageFields := cli.StringSlice{}
137 messageFieldsFlag := cli.StringSliceFlag{
138 Name: "message-fields, m",
139 Usage: "Custom JSON fields to search for the log message. (i.e. mssge, data.body.message)",
140 EnvVar: "HUMANLOG_MESSAGE_FIELDS",
141 Value: &messageFields,
142 }
143
144 timeFields := cli.StringSlice{}
145 timeFieldsFlag := cli.StringSliceFlag{
146 Name: "time-fields, t",
147 Usage: "Custom JSON fields to search for the log time. (i.e. logtime, data.body.datetime)",
148 EnvVar: "HUMANLOG_TIME_FIELDS",
149 Value: &timeFields,
150 }
151
152 levelFields := cli.StringSlice{}
153 levelFieldsFlag := cli.StringSliceFlag{
154 Name: "level-fields, l",
155 Usage: "Custom JSON fields to search for the log level. (i.e. somelevel, data.level)",
156 EnvVar: "HUMANLOG_LEVEL_FIELDS",
157 Value: &levelFields,
158 }
159
160 app := cli.NewApp()
161 app.Author = "Antoine Grondin"
162 app.Email = "[email protected]"
163 app.Name = "humanlog"
164 app.Version = semverVersion.String()
165 app.Usage = "reads structured logs from stdin, makes them pretty on stdout!"
166
167 var (
168 ctx context.Context
169 cancel context.CancelFunc
170 cfg *config.Config
171 statefile *state.State
172 promptedToUpdate *semver.Version
173 updateRes <-chan *checkForUpdateRes
174 )
175
176 app.Before = func(c *cli.Context) error {
177 ctx, cancel = signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
178
179 // read config
180 if c.IsSet(configFlag.Name) {
181 configFilepath := c.String(configFlag.Name)
182 cfgFromFlag, err := config.ReadConfigFile(configFilepath, &config.DefaultConfig)
183 if err != nil {
184 return fmt.Errorf("reading --config file %q: %v", configFilepath, err)
185 }
186 cfg = cfgFromFlag
187 } else {
188 configFilepath, err := config.GetDefaultConfigFilepath()
189 if err != nil {
190 return fmt.Errorf("looking up config file path: %v", err)
191 }
192 cfgFromDir, err := config.ReadConfigFile(configFilepath, &config.DefaultConfig)
193 if err != nil {
194 return fmt.Errorf("reading default config file: %v", err)
195 }
196 cfg = cfgFromDir
197 }
198
199 stateFilepath, err := state.GetDefaultStateFilepath()
200 if err != nil {
201 return fmt.Errorf("looking up state file path: %v", err)
202 }
203 // read state
204 statefile, err = state.ReadStateFile(stateFilepath, &state.DefaultState)
205 if err != nil {
206 return fmt.Errorf("reading default config file: %v", err)
207 }
208
209 if shouldCheckForUpdate(c, cfg, statefile) {
210 if statefile.LatestKnownVersion != nil && statefile.LatestKnownVersion.GT(semverVersion) {
211 promptedToUpdate = statefile.LatestKnownVersion
212 if shouldPromptAboutUpdate() {
213 promptToUpdate(semverVersion, *statefile.LatestKnownVersion)
214 }
215 }
216
217 req := &checkForUpdateReq{
218 arch: runtime.GOARCH,
219 os: runtime.GOOS,
220 current: version,
221 }
222 updateRes = asyncCheckForUpdate(ctx, req, cfg, statefile)
223 }
224 return nil
225 }
226 app.After = func(c *cli.Context) error {
227 cancel()
228 select {
229 case res, ok := <-updateRes:
230 if !ok {
231 return nil
232 }
233 if res.hasUpdate {
234 alreadyPromptedForSameUpdate := promptedToUpdate != nil && promptedToUpdate.GTE(res.sem)
235 if !alreadyPromptedForSameUpdate {
236 if shouldPromptAboutUpdate() {
237 promptToUpdate(semverVersion, res.sem)
238 }
239 }
240 }
241 default:
242 }
243 return nil
244 }
245 var (
246 getCtx = func(*cli.Context) context.Context { return ctx }
247 getCfg = func(*cli.Context) *config.Config { return cfg }
248 getState = func(*cli.Context) *state.State { return statefile }
249 )
250 app.Commands = append(app.Commands, versionCmd(getCtx, getCfg, getState))
251 app.Flags = []cli.Flag{configFlag, skipFlag, keepFlag, sortLongest, skipUnchanged, truncates, truncateLength, colorFlag, lightBg, timeFormat, ignoreInterrupts, messageFieldsFlag, timeFieldsFlag, levelFieldsFlag}
252 app.Action = func(c *cli.Context) error {
253 // flags overwrite config file
254 if c.IsSet(sortLongest.Name) {
255 cfg.SortLongest = ptr(c.BoolT(sortLongest.Name))
256 }
257 if c.IsSet(skipUnchanged.Name) {
258 cfg.SkipUnchanged = ptr(c.BoolT(skipUnchanged.Name))
259 }
260 if c.IsSet(truncates.Name) {
261 cfg.Truncates = ptr(c.BoolT(truncates.Name))
262 }
263 if c.IsSet(truncateLength.Name) {
264 cfg.TruncateLength = ptr(c.Int(truncateLength.Name))
265 }
266 if c.IsSet(lightBg.Name) {
267 cfg.LightBg = ptr(c.Bool(lightBg.Name))
268 }
269 if c.IsSet(timeFormat.Name) {
270 cfg.TimeFormat = ptr(c.String(timeFormat.Name))
271 }
272 if c.IsSet(colorFlag.Name) {
273 cfg.ColorMode = ptr(c.String(colorFlag.Name))
274 }
275 if c.IsSet(skipFlag.Name) {
276 cfg.Skip = ptr([]string(skip))
277 }
278 if c.IsSet(keepFlag.Name) {
279 cfg.Keep = ptr([]string(keep))
280 }
281 if c.IsSet(strings.Split(messageFieldsFlag.Name, ",")[0]) {
282 cfg.MessageFields = ptr([]string(messageFields))
283 }
284
285 if c.IsSet(strings.Split(timeFieldsFlag.Name, ",")[0]) {
286 cfg.TimeFields = ptr([]string(timeFields))
287 }
288
289 if c.IsSet(strings.Split(levelFieldsFlag.Name, ",")[0]) {
290 cfg.LevelFields = ptr([]string(levelFields))
291 }
292
293 if c.IsSet(strings.Split(ignoreInterrupts.Name, ",")[0]) {
294 cfg.Interrupt = ptr(c.Bool(strings.Split(ignoreInterrupts.Name, ",")[0]))
295 }
296
297 // apply the config
298 if *cfg.Interrupt {
299 signal.Ignore(os.Interrupt)
300 }
301
302 if len(*cfg.Skip) > 0 && len(*cfg.Keep) > 0 {
303 fatalf(c, "can only use one of %q and %q", skipFlag.Name, keepFlag.Name)
304 }
305
306 sinkOpts, errs := stdiosink.StdioOptsFrom(*cfg)
307 if len(errs) > 0 {
308 for _, err := range errs {
309 log.Printf("config error: %v", err)
310 }
311 }
312 sink := stdiosink.NewStdio(colorable.NewColorableStdout(), sinkOpts)
313 handlerOpts := humanlog.HandlerOptionsFrom(*cfg)
314
315 log.Print("reading stdin...")
316 if err := humanlog.Scan(ctx, os.Stdin, sink, handlerOpts); err != nil {
317 log.Fatalf("scanning caught an error: %v", err)
318 }
319
320 return nil
321 }
322 return app
323 }
324
325 func ptr[T any](v T) *T {
326 return &v
327 }
328
329 func mustatoi(a string) int {
330 i, err := strconv.Atoi(a)
331 if err != nil {
332 panic(err)
333 }
334 return i
335 }