]>
Commit | Line | Data |
---|---|---|
1 | package main | |
2 | ||
3 | import ( | |
4 | "context" | |
5 | "flag" | |
6 | "fmt" | |
7 | "github.com/jhalter/mobius/hotline" | |
8 | "github.com/rivo/tview" | |
9 | "go.uber.org/zap" | |
10 | "go.uber.org/zap/zapcore" | |
11 | "log" | |
12 | "os" | |
13 | "os/signal" | |
14 | "syscall" | |
15 | ) | |
16 | ||
17 | ||
18 | func main() { | |
19 | _, cancelRoot := context.WithCancel(context.Background()) | |
20 | ||
21 | sigChan := make(chan os.Signal, 1) | |
22 | signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT, os.Interrupt) | |
23 | ||
24 | version := flag.Bool("version", false, "print version and exit") | |
25 | logLevel := flag.String("log-level", "info", "Log level") | |
26 | logFile := flag.String("log-file", "", "output logs to file") | |
27 | ||
28 | flag.Parse() | |
29 | ||
30 | if *version { | |
31 | fmt.Printf("v%s\n", hotline.VERSION) | |
32 | os.Exit(0) | |
33 | } | |
34 | ||
35 | zapLvl, ok := zapLogLevel[*logLevel] | |
36 | if !ok { | |
37 | fmt.Printf("Invalid log level %s. Must be debug, info, warn, or error.\n", *logLevel) | |
38 | os.Exit(0) | |
39 | } | |
40 | ||
41 | // init DebugBuffer | |
42 | db := &hotline.DebugBuffer{ | |
43 | TextView: tview.NewTextView(), | |
44 | } | |
45 | ||
46 | cores := []zapcore.Core{newZapCore(zapLvl, db)} | |
47 | ||
48 | // Add file logger if optional log-file flag was passed | |
49 | if *logFile != "" { | |
50 | f, err := os.OpenFile(*logFile, | |
51 | os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
52 | if err != nil { | |
53 | log.Println(err) | |
54 | } | |
55 | defer f.Close() | |
56 | if err != nil { | |
57 | panic(err) | |
58 | } | |
59 | cores = append(cores, newZapCore(zapLvl, f)) | |
60 | } | |
61 | ||
62 | l := zap.New(zapcore.NewTee(cores...)) | |
63 | defer func() { _ = l.Sync() }() | |
64 | logger := l.Sugar() | |
65 | logger.Infow("Started Mobius client", "Version", hotline.VERSION) | |
66 | ||
67 | go func() { | |
68 | sig := <-sigChan | |
69 | logger.Infow("Stopping client", "signal", sig.String()) | |
70 | cancelRoot() | |
71 | }() | |
72 | ||
73 | client := hotline.NewClient("", logger) | |
74 | client.DebugBuf = db | |
75 | client.UI.Start() | |
76 | ||
77 | } | |
78 | ||
79 | func newZapCore(level zapcore.Level, syncer zapcore.WriteSyncer) zapcore.Core { | |
80 | encoderCfg := zap.NewProductionEncoderConfig() | |
81 | encoderCfg.TimeKey = "timestamp" | |
82 | encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder | |
83 | ||
84 | return zapcore.NewCore( | |
85 | zapcore.NewConsoleEncoder(encoderCfg), | |
86 | zapcore.Lock(syncer), | |
87 | level, | |
88 | ) | |
89 | } | |
90 | ||
91 | var zapLogLevel = map[string]zapcore.Level{ | |
92 | "debug": zap.DebugLevel, | |
93 | "info": zap.InfoLevel, | |
94 | "warn": zap.WarnLevel, | |
95 | "error": zap.ErrorLevel, | |
96 | } |