-
Notifications
You must be signed in to change notification settings - Fork 4
/
logger.go
67 lines (53 loc) · 1.45 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
// Copyright 2022 Azugo. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package core
import (
"os"
"strings"
"github.com/mattn/go-colorable"
"go.elastic.co/ecszap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var canColorStdout = false
func (a *App) initLogger() error {
if a.logger != nil {
return nil
}
fields := make([]zap.Field, 0, 3)
if a.AppName != "" {
fields = append(fields, zap.String("service.name", a.AppName))
}
if a.AppVer != "" {
fields = append(fields, zap.String("service.version", a.AppVer))
}
fields = append(fields, zap.String("service.environment", strings.ToLower(string(a.Env()))))
// TODO: add additional fields for logger
if canColorStdout && a.Env().IsDevelopment() {
conf := zap.NewDevelopmentEncoderConfig()
conf.EncodeLevel = zapcore.CapitalColorLevelEncoder
a.logger = zap.New(
zapcore.NewCore(
zapcore.NewConsoleEncoder(conf),
zapcore.AddSync(colorable.NewColorableStdout()),
zap.DebugLevel,
),
zap.AddCaller(),
zap.AddStacktrace(zap.ErrorLevel),
).With(fields...)
return nil
}
encoderConfig := ecszap.NewDefaultEncoderConfig()
core := ecszap.NewCore(encoderConfig, os.Stdout, zap.InfoLevel)
a.logger = zap.New(core, zap.AddCaller()).With(fields...)
return nil
}
func (a *App) Log() *zap.Logger {
if a.logger == nil {
if err := a.initLogger(); err != nil {
panic(err)
}
}
return a.logger
}