forked from aws/amazon-cloudwatch-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
106 lines (91 loc) · 2.49 KB
/
logger.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
package logger
import (
"io"
"github.com/influxdata/wlog"
"go.uber.org/zap"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
var (
loggerLevel zap.AtomicLevel
)
type TelegrafWrapperEncoder struct {
zapcore.Encoder
}
func NewLogger(writer io.Writer, level zap.AtomicLevel) (*zap.Logger, []zap.Option) {
core := zapcore.NewCore(
createTelegrafWrapperEncoder(),
zapcore.AddSync(writer),
loggerLevel,
)
option := zap.WrapCore(func(zapcore.Core) zapcore.Core {
return core
})
logger := zap.New(core)
defer logger.Sync()
return logger, []zap.Option{option}
}
func getLoggingOptions(writer io.Writer) []zap.Option {
core := zapcore.NewCore(
createTelegrafWrapperEncoder(),
zapcore.AddSync(writer),
loggerLevel,
)
option := zap.WrapCore(func(zapcore.Core) zapcore.Core {
return core
})
return []zap.Option{option}
}
func createTelegrafWrapperEncoder() TelegrafWrapperEncoder {
return TelegrafWrapperEncoder{
zapcore.NewJSONEncoder(newProductionEncoderConfig()),
}
}
func SetLevel(level zap.AtomicLevel) {
loggerLevel.SetLevel(level.Level())
}
func (t TelegrafWrapperEncoder) EncodeEntry(e zapcore.Entry, f []zapcore.Field) (*buffer.Buffer, error) {
entry, err := t.Encoder.EncodeEntry(e, f)
if err != nil {
return nil, err
}
buf := buffer.NewPool().Get()
levelLetter := ConvertToLetterLevel(e.Level)
buf.AppendString(levelLetter + "! ")
buf.AppendString(entry.String())
return buf, nil
}
func (t TelegrafWrapperEncoder) Clone() zapcore.Encoder {
return TelegrafWrapperEncoder{
zapcore.NewJSONEncoder(newProductionEncoderConfig()),
}
}
func newProductionEncoderConfig() zapcore.EncoderConfig {
return zapcore.EncoderConfig{
NameKey: "logger",
CallerKey: "caller",
FunctionKey: zapcore.OmitKey,
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeCaller: zapcore.ShortCallerEncoder,
}
}
func ConvertToAtomicLevel(level wlog.Level) zap.AtomicLevel {
if level == wlog.DEBUG {
return zap.NewAtomicLevelAt(zapcore.DebugLevel)
} else if level == wlog.WARN {
return zap.NewAtomicLevelAt(zapcore.WarnLevel)
} else if level == wlog.ERROR {
return zap.NewAtomicLevelAt(zapcore.ErrorLevel)
}
return zap.NewAtomicLevelAt(zapcore.InfoLevel)
}
func ConvertToLetterLevel(l zapcore.Level) string {
return string(l.CapitalString()[0])
}
func init() {
loggerLevel = zap.NewAtomicLevelAt(zapcore.InfoLevel)
}