-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdlogr.go
286 lines (241 loc) · 6.3 KB
/
sdlogr.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Package sdlogr: another implementation of logr interface with addition of systemd specific prefixes (severity levels). This logger is meant for apps/services that are started via systemd and want to send their logs to system journal.
package sdlogr
import (
"bytes"
"fmt"
"github.com/go-logr/logr"
"io"
"os"
"reflect"
"runtime"
"strconv"
)
const (
// from systemd/sd-daemon.h
//
// #define SD_EMERG "<0>" /* system is unusable */
// #define SD_ALERT "<1>" /* action must be taken immediately */
// #define SD_CRIT "<2>" /* critical conditions */
// #define SD_ERR "<3>" /* error conditions */
// #define SD_WARNING "<4>" /* warning conditions */
// #define SD_NOTICE "<5>" /* normal but significant condition */
// #define SD_INFO "<6>" /* informational */
// #define SD_DEBUG "<7>" /* debug-level messages */
sdLvlError = "<3>"
sdLvlInfo = "<6>"
)
const emptyStringPlaceholder = "\"\""
var mergeSeparators = [2]string{": ", ", "}
type Options struct {
// Depth biases the assumed number of call frames to the "true" caller.
// Values less than zero will be treated as zero.
Depth int
// Verbosity tells sdlogr which V logs to produce. Higher values enable
// more logs. Info logs at or below this level will be written, while logs
// above this level will be discarded.
Verbosity int
// LogCallerInfo if this is false caller file name and line number will not be logged in logr.Info. Default is true, caller file name and line number are always logged in logr.Error.
LogCallerInfo bool
// Out where to send logs. Defaults to os.Stdout
Out io.Writer
}
// New returns a logr.Logger
func New() logr.Logger {
return NewWithOptions(Options{LogCallerInfo: true})
}
// NewWithOptions returns a logr.Logger
func NewWithOptions(opts Options) logr.Logger {
if opts.Depth < 0 {
opts.Depth = 0
}
if opts.Verbosity < 0 {
opts.Verbosity = 0
}
if opts.Out == nil {
opts.Out = os.Stdout
}
l := sdLogr{
level: opts.Verbosity,
depth: opts.Depth + 1,
logCallerInfo: opts.LogCallerInfo,
out: opts.Out,
valuesMap: make(map[string]string, 1),
}
return logr.New(&l)
}
type sdLogr struct {
level int
depth int
prefix string
valuesMap map[string]string
valuesStr string
out io.Writer
logCallerInfo bool
}
func (l *sdLogr) Init(info logr.RuntimeInfo) {
if info.CallDepth < 0 {
return
}
l.depth += info.CallDepth
}
func (l *sdLogr) Enabled(level int) bool {
return level <= l.level
}
func (l *sdLogr) Info(_ int, msg string, kvList ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 512))
buf.WriteString(sdLvlInfo)
// we do npt log if there is no message or values
hasData := false
if len(l.prefix) > 0 {
buf.WriteString(l.prefix + ": ")
}
if l.logCallerInfo {
if _, file, line, ok := runtime.Caller(l.depth); ok {
buf.WriteString(file[getLastSlashPos(file)+1:] + ": " + strconv.Itoa(line) + ", ")
} else {
buf.WriteString("???: 0, ")
}
}
if msg != "" {
buf.WriteString(msg + ", ")
hasData = true
}
if l.valuesStr != "" {
buf.WriteString(l.valuesStr)
hasData = true
}
kvLen := len(kvList)
if kvLen > 0 {
bufferKv(buf, kvList, kvLen)
hasData = true
}
if hasData {
write(l.out, buf)
}
}
func (l *sdLogr) Error(err error, msg string, kvList ...interface{}) {
buf := bytes.NewBuffer(make([]byte, 0, 512))
buf.WriteString(sdLvlError)
if len(l.prefix) > 0 {
buf.WriteString(l.prefix + ": ")
}
if _, file, line, ok := runtime.Caller(l.depth); ok {
buf.WriteString(file[getLastSlashPos(file)+1:] + ": " + strconv.Itoa(line) + ", ")
} else {
buf.WriteString("???: 0, ")
}
if err != nil {
buf.WriteString(err.Error() + ", ")
} else {
buf.WriteString("<nil>, ")
}
if msg != "" {
buf.WriteString(msg + ", ")
}
if l.valuesStr != "" {
buf.WriteString(l.valuesStr)
}
kvLen := len(kvList)
if kvLen > 0 {
bufferKv(buf, kvList, kvLen)
}
write(l.out, buf)
}
// WithName returns a new logr.Logger with the specified name appended, '/' character is used to separate multiple names.
func (l sdLogr) WithName(name string) logr.LogSink {
if len(l.prefix) > 0 {
l.prefix += "/"
}
l.prefix += name
return &l
}
func (l sdLogr) WithValues(kvList ...interface{}) logr.LogSink {
// because we have data before the values string...
n := len(kvList)
if n == 0 {
return &l
}
if (n & 1) != 0 {
// for some reason a value is missing
// let's add an empty string
kvList = append(kvList, emptyStringPlaceholder)
n++
}
l.valuesStr = ""
var lastKey *string
for i := 0; i < n; i++ {
kvi := kvList[i]
if kvi == "" {
kvi = emptyStringPlaceholder
}
kv := fmt.Sprintf("%v", deref(kvi))
if (i & 1) == 0 {
// kv is key
lastKey = &kv
} else {
// kv is value
l.valuesMap[*lastKey] = kv
}
}
for k, v := range l.valuesMap {
l.valuesStr += k + ": " + fmt.Sprintf("%v", deref(v)) + ", "
}
return &l
}
func (l sdLogr) WithCallDepth(depth int) logr.LogSink {
l.depth += depth
return &l
}
// UnmarshalStruct converts struct to string (including keys) using "%+v" format
func UnmarshalStruct(i interface{}) string {
return fmt.Sprintf("%+v", deref(i))
}
func write(out io.Writer, buf *bytes.Buffer) {
// cut off extra separator and add LF(10)
newLen := buf.Len() - 1
finalBytes := buf.Bytes()[:newLen]
newLen -= 1
if finalBytes[newLen] != 10 {
finalBytes[newLen] = 10
}
_, _ = out.Write(finalBytes)
}
func bufferKv(buf *bytes.Buffer, kvList []interface{}, kvLen int) {
for i := 0; i < kvLen; i++ {
v := kvList[i]
if v == "" {
v = emptyStringPlaceholder
}
_, _ = fmt.Fprintf(buf, "%v", deref(v))
buf.WriteString(mergeSeparators[i&1])
}
}
func deref(i interface{}) interface{} {
// try Type switch first
switch i.(type) {
case string, int, bool, uint, int8, int16, int32, int64, uint8, uint16, uint32, uint64, uintptr, []string, []int, []bool, []uint, []int8, []int16, []int32, []int64, []uint8, []uint16, []uint32, []uint64, []uintptr, error:
return i
default:
// use reflect
v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return nil
} else {
return v.Elem().Interface()
}
}
return i
}
}
func getLastSlashPos(str string) int {
i := len(str) - 1
for ; i > 0; i-- {
if str[i] == '/' {
break
}
}
return i
}
var _ logr.LogSink = &sdLogr{}
var _ logr.CallDepthLogSink = &sdLogr{}