about summary refs log tree commit diff stats
path: root/log/log.go
blob: 053288a8cb1accc67e5d6d8fba174751bf89d3d0 (plain)
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
package log

import (
	"os"

	zaplogfmt "github.com/sykesm/zap-logfmt"
	prettyconsole "github.com/thessem/zap-prettyconsole"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"moul.io/zapfilter"
)

type Logger struct {
	logger *zap.SugaredLogger
}

func (l Logger) DPanic(msg string, rest ...any) {
	l.logger.DPanicw(msg, rest...)
}
func (l Logger) Debug(msg string, rest ...any) {
	l.logger.Debugw(msg, rest...)
}
func (l Logger) Info(msg string, rest ...any) {
	l.logger.Infow(msg, rest...)
}
func (l Logger) Warn(msg string, rest ...any) {
	l.logger.Warnw(msg, rest...)
}
func (l Logger) Error(msg string, rest ...any) {
	l.logger.Errorw(msg, rest...)
}
func (l Logger) Panic(msg string, rest ...any) {
	l.logger.Panicw(msg, rest...)
}
func (l Logger) Fatal(msg string, rest ...any) {
	l.logger.Fatalw(msg, rest...)
}

func (l Logger) Named(name string) *Logger {
	return &Logger{
		logger: l.logger.Named(name),
	}
}
func (l Logger) With(args ...any) *Logger {
	return &Logger{
		logger: l.logger.With(args...),
	}
}

func (l Logger) GetLogger() *zap.Logger {
	return l.logger.Desugar()
}

func getLevelFromEnv() (zapcore.Level, error) {
	if str, found := os.LookupEnv("LOG_LEVEL"); found {
		l, err := zapcore.ParseLevel(str)

		return l, err
	}

	return zap.InfoLevel, nil
}

var atom zap.AtomicLevel

func Configure(isProduction bool) *Logger {
	atom = zap.NewAtomicLevel()
	level, err := getLevelFromEnv()
	if err != nil {
		panic(err)
	}
	atom.SetLevel(level)

	var filter zapfilter.FilterFunc
	if debug := os.Getenv("DEBUG"); debug != "" {
		filter = zapfilter.Any(zapfilter.MinimumLevel(level), zapfilter.ByNamespaces(debug))
	} else {
		filter = zapfilter.MinimumLevel(level)
	}

	var cfg zapcore.EncoderConfig
	var enc zapcore.Encoder
	if isProduction {
		cfg = zap.NewProductionEncoderConfig()
		cfg.TimeKey = ""
		enc = zaplogfmt.NewEncoder(cfg)
	} else {
		cfg = prettyconsole.NewEncoderConfig()
		cfg.TimeKey = ""
		enc = prettyconsole.NewEncoder(cfg)
	}
	log := zap.New(
		zapfilter.NewFilteringCore(zapcore.NewCore(enc, os.Stderr, zap.DebugLevel), filter),
	)

	zap.ReplaceGlobals(log)
	zap.RedirectStdLog(log)

	return &Logger{
		logger: log.WithOptions(zap.AddCallerSkip(1)).Sugar(),
	}
}

func SetLevel(level zapcore.Level) {
	atom.SetLevel(level)
}