-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlog2oms.go
113 lines (93 loc) · 2.52 KB
/
log2oms.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
package main
import (
"fmt"
"os"
"strings"
"time"
"github.com/hpcloud/tail"
"github.com/yangl900/log2oms/logclient"
)
const (
envLogFile = "LOG2OMS_LOG_FILE"
envLogType = "LOG2OMS_LOG_TYPE"
envWorkspaceID = "LOG2OMS_WORKSPACE_ID"
envWorkspaceSecret = "LOG2OMS_WORKSPACE_SECRET"
envMetadataPrefix = "LOG2OMS_METADATA_"
)
var (
batchSizeInLines = 100000
requestSizeLimit = 1024 * 1024 * 8
)
func logLines(client *logclient.LogClient, lines []string) {
err := client.PostMessages(lines, time.Now().UTC())
if err != nil {
fmt.Println(err)
}
}
func metadata() map[string]string {
metadata := make(map[string]string)
metadata["Hostname"], _ = os.Hostname()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
if strings.HasPrefix(pair[0], envMetadataPrefix) {
key := strings.TrimPrefix(pair[0], envMetadataPrefix)
metadata[key] = pair[1]
}
}
return metadata
}
func main() {
workspaceID, workspaceSecret := os.Getenv(envWorkspaceID), os.Getenv(envWorkspaceSecret)
if workspaceID == "" || workspaceSecret == "" {
fmt.Printf("Workspace Id and secret not defined in environment variable '%s' and '%s'\n", envWorkspaceID, envWorkspaceSecret)
return
}
logfile := os.Getenv(envLogFile)
if logfile == "" {
if len(os.Args) < 2 {
fmt.Printf("Neither '%s' environment variable nor command line parameter specified.\n", envLogFile)
return
}
logfile = os.Args[1]
}
logType := os.Getenv(envLogType)
if logType == "" {
logType = "container_logs"
}
metadata := metadata()
for m := range metadata {
fmt.Printf("[LOG2OMS][%s] %s = %s\n", time.Now().UTC().Format(time.RFC3339), m, metadata[m])
}
fmt.Printf("[LOG2OMS][%s] Start tail logs from: %s\n", time.Now().UTC().Format(time.RFC3339), logfile)
client := logclient.NewLogClient(workspaceID, workspaceSecret, logType, metadata)
t, err := tail.TailFile(logfile, tail.Config{ReOpen: true, Follow: true})
if err != nil {
fmt.Println(err)
return
}
lines := []string{}
byteCount := 0
for {
select {
case line := <-t.Lines:
if line.Err != nil {
fmt.Println(line.Err)
} else {
fmt.Printf("[%s] %s\n", line.Time.UTC().Format(time.RFC3339), line.Text)
}
lines = append(lines, line.Text)
byteCount += len(line.Text)
if len(lines) >= batchSizeInLines || byteCount >= requestSizeLimit {
logLines(&client, lines)
lines = []string{}
byteCount = 0
}
case <-time.After(time.Second * 5):
if len(lines) > 0 {
logLines(&client, lines)
lines = []string{}
byteCount = 0
}
}
}
}