forked from bsphere/le_go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathle.go
247 lines (205 loc) · 5.99 KB
/
le.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Package le_go provides a Golang client library for logging to
// logentries.com over a TCP connection.
//
// it uses an access token for sending log events.
package le_go
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"net"
"os"
"sync"
)
// Logger represents a Logentries logger,
// it holds the open TCP connection, access token, prefix and flags.
//
// all Logger operations are thread safe and blocking,
// log operations can be invoked in a non-blocking way by calling them from
// a goroutine.
type Logger struct {
conn net.Conn // nil if this logger is closed and should not reopen
flag int
mu sync.Mutex
prefix string
endpoint string
token string
}
const (
asciiLineSep = 0x0A // "\n"
asciiSpace = 0x20 // " "
)
var unicodeLineSep = []byte{0xE2, 0x80, 0xA8} // "\u2028"
var (
ErrClosed = errors.New("le: use of closed connection")
)
// Connect creates a new Logger instance and opens a TCP connection to
// logentries.com,
// The token can be generated at logentries.com by adding a new log,
// choosing manual configuration and token based TCP connection.
func Connect(token string) (*Logger, error) {
var endpoint string
if envEndpoint, found := os.LookupEnv("INSIGHTOPS_ENDPOINT"); found {
endpoint = envEndpoint
} else {
endpoint = "data.logentries.com"
}
if envToken, found := os.LookupEnv("INSIGHTOPS_TOKEN"); found {
token = envToken
}
conn, err := openConnection(endpoint)
if err != nil {
return nil, err
}
logger := Logger{
conn: conn,
endpoint: endpoint,
token: token,
}
return &logger, nil
}
// Close closes the TCP connection to logentries.com
func (logger *Logger) Close() error {
logger.mu.Lock()
defer logger.mu.Unlock()
if logger.conn == nil {
return ErrClosed
}
err := logger.conn.Close()
logger.conn = nil
return err
}
// Opens a TCP connection to logentries.com
func openConnection(endpoint string) (net.Conn, error) {
conn, err := tls.Dial("tcp", endpoint+":443", &tls.Config{})
return conn, err
}
// Fatal is same as Print() but calls to os.Exit(1)
func (logger *Logger) Fatal(v ...interface{}) {
logger.Output(2, fmt.Sprint(v...))
os.Exit(1)
}
// Fatalf is same as Printf() but calls to os.Exit(1)
func (logger *Logger) Fatalf(format string, v ...interface{}) {
logger.Output(2, fmt.Sprintf(format, v...))
os.Exit(1)
}
// Fatalln is same as Println() but calls to os.Exit(1)
func (logger *Logger) Fatalln(v ...interface{}) {
logger.Output(2, fmt.Sprintln(v...))
os.Exit(1)
}
// Flags returns the logger flags
func (logger *Logger) Flags() int {
return logger.flag
}
// Output does the actual writing to the TCP connection
func (logger *Logger) Output(calldepth int, s string) error {
_, err := logger.Write([]byte(s))
return err
}
// Panic is same as Print() but calls to panic
func (logger *Logger) Panic(v ...interface{}) {
s := fmt.Sprint(v...)
logger.Output(2, s)
panic(s)
}
// Panicf is same as Printf() but calls to panic
func (logger *Logger) Panicf(format string, v ...interface{}) {
s := fmt.Sprintf(format, v...)
logger.Output(2, s)
panic(s)
}
// Panicln is same as Println() but calls to panic
func (logger *Logger) Panicln(v ...interface{}) {
s := fmt.Sprintln(v...)
logger.Output(2, s)
panic(s)
}
// Prefix returns the logger prefix
func (logger *Logger) Prefix() string {
return logger.prefix
}
// Print logs a message
func (logger *Logger) Print(v ...interface{}) {
logger.Output(2, fmt.Sprint(v...))
}
// Printf logs a formatted message
func (logger *Logger) Printf(format string, v ...interface{}) {
logger.Output(2, fmt.Sprintf(format, v...))
}
// Println logs a message with a linebreak
func (logger *Logger) Println(v ...interface{}) {
logger.Output(2, fmt.Sprintln(v...))
}
// SetFlags sets the logger flags
func (logger *Logger) SetFlags(flag int) {
logger.flag = flag
}
// SetPrefix sets the logger prefix
func (logger *Logger) SetPrefix(prefix string) {
logger.prefix = prefix
}
// Write writes a bytes array to the Logentries TCP connection,
// it adds the access token and prefix and also replaces
// line breaks with the unicode \u2028 character
func (logger *Logger) Write(p []byte) (int, error) {
// Construct the message once, outside of any mutex
buf := logger.makeBuf(p)
// Accessing logger.conn must be done with a mutex
logger.mu.Lock()
defer logger.mu.Unlock()
if logger.conn == nil {
return 0, ErrClosed
}
_, err := logger.conn.Write(buf)
if err == nil {
return len(p), nil
}
// First write failed. Try reconnecting and then a second write; if that fails give up. If
// we wanted to keep trying we would have to maintain a queue and a separate goroutine.
// Ignore errors closing (including "already closed")
logger.conn.Close()
newConn, err := openConnection(logger.endpoint)
if err != nil {
return 0, err
}
logger.conn = newConn
_, err = logger.conn.Write(buf)
return len(p), err
}
// bytes.IndexByte exists but not bytes.CountByte
func countByte(s []byte, c byte) int {
return bytes.Count(s, []byte{c})
}
// makeBuf constructs the logger buffer
func (logger *Logger) makeBuf(p []byte) []byte {
// Pre-allocate a buffer of the correct size
capacity := len(logger.token) + 1
capacity += len(logger.prefix) + 1
capacity += len(p) // nominal payload size (before replacement)
capacity += countByte(p, asciiLineSep) * 2 // 1-byte "\n"s replaced with 3-byte "\u2028"s
capacity += 1 // trailing newline
buf := make([]byte, 0, capacity)
// Buffer header
buf = append(buf, logger.token...)
buf = append(buf, asciiSpace)
buf = append(buf, logger.prefix...)
buf = append(buf, asciiSpace)
// We need to convert the "\n" runes into unicode "\u2028" line separators. This is done at
// the byte level to avoid copying data back and forth from strings.
for {
i := bytes.IndexByte(p, asciiLineSep)
if i < 0 {
buf = append(buf, p...)
break
}
buf = append(buf, p[:i]...)
buf = append(buf, unicodeLineSep...)
p = p[i+1:]
}
// Buffer must end with an ascii line separator
buf = append(buf, asciiLineSep)
return buf
}