forked from omriharel/deej
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
64 lines (49 loc) · 1.64 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
package deej
import (
"fmt"
"path/filepath"
"time"
"github.com/omriharel/deej/util"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
buildTypeNone = ""
buildTypeDev = "dev"
buildTypeRelease = "release"
logDirectory = "logs"
logFilename = "deej-latest-run.log"
)
// NewLogger provides a logger instance for the whole program
func NewLogger(buildType string) (*zap.SugaredLogger, error) {
var loggerConfig zap.Config
// release: info and above, log to file only (no UI)
if buildType == buildTypeRelease {
if err := util.EnsureDirExists(logDirectory); err != nil {
return nil, fmt.Errorf("ensure log directory exists: %w", err)
}
loggerConfig = zap.NewProductionConfig()
loggerConfig.OutputPaths = []string{filepath.Join(logDirectory, logFilename)}
loggerConfig.Encoding = "console"
// development: debug and above, log to stderr only, colorful
} else {
loggerConfig = zap.NewDevelopmentConfig()
// make it colorful
loggerConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
// all build types: make it readable
loggerConfig.EncoderConfig.EncodeCaller = nil
loggerConfig.EncoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
loggerConfig.EncoderConfig.EncodeName = func(s string, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(fmt.Sprintf("%-27s", s))
}
logger, err := loggerConfig.Build()
if err != nil {
return nil, fmt.Errorf("create zap logger: %w", err)
}
// no reason not to use the sugared logger - it's fast enough for anything we're gonna do
sugar := logger.Sugar()
return sugar, nil
}