-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
223 lines (187 loc) · 5.21 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
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
package common
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/microsoft/ApplicationInsights-Go/appinsights"
)
type LogHandler interface {
Initialize(*log.Logger) error
Receive(string) error
}
var (
flagIkey string
flagEndpoint string
flagRole string
flagRoleInstance string
flagInfile string
flagOutfile string
flagCustom customProperties
flagFlushWait time.Duration
flagDebug bool
flagQuiet bool
tclient appinsights.TelemetryClient
)
func InitFlags() {
flag.StringVar(&flagIkey, "ikey", "", "ApplicationInsights instrumentation key (required)")
flag.StringVar(&flagEndpoint, "endpoint", "", "ApplicationInsights ingestion endpoint")
flag.StringVar(&flagRole, "role", "", "Telemetry role name. Defaults to the machine hostname")
flag.StringVar(&flagRoleInstance, "roleinstance", "", "Telemetry role instance. Defaults to the machine hostname")
flag.StringVar(&flagInfile, "in", "", "Input file, or '-' for stdin (required)")
flag.StringVar(&flagOutfile, "out", "", "Output file, '-' for stdout, 'stderr' for stderr")
flag.DurationVar(&flagFlushWait, "flush", 3*time.Second, "Timeout to flush telemetry when shutting down")
flag.BoolVar(&flagDebug, "debug", false, "Show debugging output")
flag.BoolVar(&flagQuiet, "quiet", false, "Don't write any output messages")
flag.Var(&flagCustom, "custom", "Include custom property in telemetry like 'key=value'. Can be used multiple times")
}
func Start(name string, logHandler LogHandler) {
if flagDebug {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
appinsights.NewDiagnosticsMessageListener(writeAiLog)
} else {
log.SetOutput(ioutil.Discard)
}
if flagInfile == "" {
fmt.Fprintln(os.Stderr, "Must specify input file. See -help for usage.")
os.Exit(1)
}
hostname, _ := os.Hostname()
if flagRole == "" {
flagRole = hostname
}
if flagRoleInstance == "" {
flagRoleInstance = hostname
}
if flagIkey == "" {
fmt.Fprintln(os.Stderr, "Must specify instrumentation key. See -help for usage.")
os.Exit(1)
}
tconfig := appinsights.NewTelemetryConfiguration(flagIkey)
if flagEndpoint != "" {
tconfig.EndpointUrl = flagEndpoint
}
tclient = appinsights.NewTelemetryClientFromConfig(tconfig)
// Propagate custom flags to common properties
for k, v := range flagCustom {
tclient.Context().CommonProperties[k] = v
}
msgs := log.New(os.Stderr, fmt.Sprintf("%s: ", name), log.Ldate|log.Ltime)
if flagQuiet {
msgs.SetOutput(ioutil.Discard)
}
cloud := tclient.Context().Tags.Cloud()
cloud.SetRole(flagRole)
cloud.SetRoleInstance(flagRoleInstance)
var logWriter *LogWriter
if flagOutfile != "" {
var err error
logWriter, err = NewLogWriter(flagOutfile)
if err != nil {
msgs.Printf("Error initializing log writer: %s\n", err.Error())
os.Exit(1)
}
} else {
logWriter = NewNilLogWriter()
}
logReader, err := MakeLogReader(flagInfile)
if err != nil {
msgs.Printf("Error initializing log reader: %s\n", err.Error())
os.Exit(1)
}
err = logHandler.Initialize(msgs)
if err != nil {
msgs.Printf("Error initializing log handler: %s\n", err.Error())
os.Exit(1)
}
signalc := make(chan os.Signal, 2)
signal.Notify(signalc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
done := make(chan bool)
go readLoop(logReader, logWriter, logHandler, msgs, done)
for {
select {
case sig := <-signalc:
msgs.Println(sig.String())
switch sig {
case syscall.SIGHUP:
msgs.Println("Resetting logfile")
logReader.Reset()
case syscall.SIGINT, syscall.SIGTERM:
logReader.Close()
// Begin flush of AI client
tclient.Channel().Flush()
// Wait for done
select {
case <-done:
break
case <-time.After(time.Duration(250 * time.Millisecond)):
break
}
logWriter.Close()
// Close down telemetry channel and try to send out any remaining events.
select {
case <-tclient.Channel().Close(flagFlushWait):
break
case <-time.After(flagFlushWait):
break
}
os.Exit(-int(sig.(syscall.Signal)))
}
case <-done:
// Flush out events and close down AI sender.
select {
case <-tclient.Channel().Close(flagFlushWait):
break
case <-time.After(flagFlushWait):
break
}
os.Exit(0)
}
}
}
func readLoop(logReader *LogReader, logWriter *LogWriter, logHandler LogHandler, msgs *log.Logger, done chan bool) {
main:
for {
select {
case event := <-logReader.events:
if event.data != "" {
if logWriter != nil {
logWriter.Write(event.data)
}
err := logHandler.Receive(event.data)
if err != nil {
msgs.Println(fmt.Sprintf("Error processing log line. Error: %s Original log line: %s", err.Error(), event.data))
}
}
if event.err != nil {
msgs.Println(event.err.Error())
}
if event.closed {
msgs.Println("Input closed.")
break main
}
case event := <-logWriter.events:
if event.err != nil {
msgs.Printf("Log output encountered error: %s", event.err.Error())
}
if event.closed {
msgs.Println("Log output closed. Aborting.")
break main
}
}
}
done <- true
}
func Track(t appinsights.Telemetry) {
if t != nil {
tclient.Track(t)
}
}
func writeAiLog(msg string) error {
log.Println(msg)
return nil
}