forked from pingcap/tidb
/
log.go
279 lines (240 loc) · 7.87 KB
/
log.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
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package logutil
import (
"context"
"encoding/json"
"fmt"
"os"
"runtime/trace"
"time"
gzap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
"github.com/opentracing/opentracing-go"
tlog "github.com/opentracing/opentracing-go/log"
"github.com/pingcap/errors"
"github.com/pingcap/log"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
// DefaultLogMaxSize is the default size of log files.
DefaultLogMaxSize = 300 // MB
// DefaultLogFormat is the default format of the log.
DefaultLogFormat = "text"
// DefaultSlowThreshold is the default slow log threshold in millisecond.
DefaultSlowThreshold = 300
// DefaultSlowTxnThreshold is the default slow txn log threshold in ms.
DefaultSlowTxnThreshold = 0
// DefaultQueryLogMaxLen is the default max length of the query in the log.
DefaultQueryLogMaxLen = 4096
// DefaultRecordPlanInSlowLog is the default value for whether enable log query plan in the slow log.
DefaultRecordPlanInSlowLog = 1
// DefaultTiDBEnableSlowLog enables TiDB to log slow queries.
DefaultTiDBEnableSlowLog = true
)
// EmptyFileLogConfig is an empty FileLogConfig.
var EmptyFileLogConfig = FileLogConfig{}
// FileLogConfig serializes file log related config in toml/json.
type FileLogConfig struct {
log.FileLogConfig
}
// NewFileLogConfig creates a FileLogConfig.
func NewFileLogConfig(maxSize uint) FileLogConfig {
return FileLogConfig{FileLogConfig: log.FileLogConfig{
MaxSize: int(maxSize),
},
}
}
// LogConfig serializes log related config in toml/json.
type LogConfig struct {
log.Config
// SlowQueryFile filename, default to File log config on empty.
SlowQueryFile string
}
// NewLogConfig creates a LogConfig.
func NewLogConfig(level, format, slowQueryFile string, fileCfg FileLogConfig, disableTimestamp bool, opts ...func(*log.Config)) *LogConfig {
c := &LogConfig{
Config: log.Config{
Level: level,
Format: format,
DisableTimestamp: disableTimestamp,
File: fileCfg.FileLogConfig,
},
SlowQueryFile: slowQueryFile,
}
for _, opt := range opts {
opt(&c.Config)
}
return c
}
const (
// SlowLogTimeFormat is the time format for slow log.
SlowLogTimeFormat = time.RFC3339Nano
// OldSlowLogTimeFormat is the first version of the the time format for slow log, This is use for compatibility.
OldSlowLogTimeFormat = "2006-01-02-15:04:05.999999999 -0700"
)
// SlowQueryLogger is used to log slow query, InitLogger will modify it according to config file.
var SlowQueryLogger = log.L()
// InitLogger initializes a logger with cfg.
func InitLogger(cfg *LogConfig, opts ...zap.Option) error {
opts = append(opts, zap.AddStacktrace(zapcore.FatalLevel))
gl, props, err := log.InitLogger(&cfg.Config, opts...)
if err != nil {
return errors.Trace(err)
}
log.ReplaceGlobals(gl, props)
// init dedicated logger for slow query log
SlowQueryLogger, _, err = newSlowQueryLogger(cfg)
if err != nil {
return errors.Trace(err)
}
initGRPCLogger(gl)
return nil
}
func initGRPCLogger(gl *zap.Logger) {
level := zapcore.ErrorLevel
verbosity := 0
if len(os.Getenv("GRPC_DEBUG")) > 0 {
verbosity = 999
level = zapcore.DebugLevel
}
newgl := gl.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
oldcore, ok := core.(*log.TextIOCore)
if !ok {
return oldcore
}
newcore := oldcore.Clone()
leveler := zap.NewAtomicLevel()
leveler.SetLevel(level)
newcore.LevelEnabler = leveler
return newcore
}))
gzap.ReplaceGrpcLoggerV2WithVerbosity(newgl, verbosity)
}
// ReplaceLogger replace global logger instance with given log config.
func ReplaceLogger(cfg *LogConfig, opts ...zap.Option) error {
opts = append(opts, zap.AddStacktrace(zapcore.FatalLevel))
gl, props, err := log.InitLogger(&cfg.Config, opts...)
if err != nil {
return errors.Trace(err)
}
log.ReplaceGlobals(gl, props)
cfgJSON, err := json.Marshal(&cfg.Config)
if err != nil {
return errors.Trace(err)
}
SlowQueryLogger, _, err = newSlowQueryLogger(cfg)
if err != nil {
return errors.Trace(err)
}
log.S().Infof("replaced global logger with config: %s", string(cfgJSON))
return nil
}
// SetLevel sets the zap logger's level.
func SetLevel(level string) error {
l := zap.NewAtomicLevel()
if err := l.UnmarshalText([]byte(level)); err != nil {
return errors.Trace(err)
}
log.SetLevel(l.Level())
return nil
}
type ctxLogKeyType struct{}
// CtxLogKey indicates the context key for logger
// public for test usage.
var CtxLogKey = ctxLogKeyType{}
// Logger gets a contextual logger from current context.
// contextual logger will output common fields from context.
func Logger(ctx context.Context) *zap.Logger {
if ctxlogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {
return ctxlogger
}
return log.L()
}
// BgLogger is alias of `logutil.BgLogger()`
func BgLogger() *zap.Logger {
return log.L()
}
// WithConnID attaches connId to context.
func WithConnID(ctx context.Context, connID uint64) context.Context {
var logger *zap.Logger
if ctxLogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {
logger = ctxLogger
} else {
logger = log.L()
}
return context.WithValue(ctx, CtxLogKey, logger.With(zap.Uint64("conn", connID)))
}
// WithTraceLogger attaches trace identifier to context
func WithTraceLogger(ctx context.Context, connID uint64) context.Context {
var logger *zap.Logger
if ctxLogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {
logger = ctxLogger
} else {
logger = log.L()
}
return context.WithValue(ctx, CtxLogKey, wrapTraceLogger(ctx, connID, logger))
}
func wrapTraceLogger(ctx context.Context, connID uint64, logger *zap.Logger) *zap.Logger {
return logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
tl := &traceLog{ctx: ctx}
// cfg.Format == "", never return error
enc, _ := log.NewTextEncoder(&log.Config{})
traceCore := log.NewTextCore(enc, tl, tl).With([]zapcore.Field{zap.Uint64("conn", connID)})
return zapcore.NewTee(traceCore, core)
}))
}
type traceLog struct {
ctx context.Context
}
func (*traceLog) Enabled(_ zapcore.Level) bool {
return true
}
func (t *traceLog) Write(p []byte) (n int, err error) {
trace.Log(t.ctx, "log", string(p))
return len(p), nil
}
func (*traceLog) Sync() error {
return nil
}
// WithKeyValue attaches key/value to context.
func WithKeyValue(ctx context.Context, key, value string) context.Context {
var logger *zap.Logger
if ctxLogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {
logger = ctxLogger
} else {
logger = log.L()
}
return context.WithValue(ctx, CtxLogKey, logger.With(zap.String(key, value)))
}
// TraceEventKey presents the TraceEventKey in span log.
const TraceEventKey = "event"
// Event records event in current tracing span.
func Event(ctx context.Context, event string) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span.LogFields(tlog.String(TraceEventKey, event))
}
}
// Eventf records event in current tracing span with format support.
func Eventf(ctx context.Context, format string, args ...interface{}) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span.LogFields(tlog.String(TraceEventKey, fmt.Sprintf(format, args...)))
}
}
// SetTag sets tag kv-pair in current tracing span
func SetTag(ctx context.Context, key string, value interface{}) {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span.SetTag(key, value)
}
}