arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/log/log.go
log/log.goRaw
  1package log
  2
  3import (
  4	"fmt"
  5	"strings"
  6	"time"
  7
  8	"github.com/hermeznetwork/tracerr"
  9	"go.uber.org/zap"
 10	"go.uber.org/zap/zapcore"
 11)
 12
 13var log *zap.SugaredLogger
 14
 15func init() {
 16	// default level: debug
 17	Init("debug", []string{"stdout"})
 18}
 19
 20// Init the logger with defined level. outputs defines the outputs where the
 21// logs will be sent. By default outputs contains "stdout", which prints the
 22// logs at the output of the process. To add a log file as output, the path
 23// should be added at the outputs array. To avoid printing the logs but storing
 24// them on a file, can use []string{"pathtofile.log"}
 25func Init(levelStr string, outputs []string) {
 26	var level zap.AtomicLevel
 27	err := level.UnmarshalText([]byte(levelStr))
 28	if err != nil {
 29		panic(fmt.Errorf("Error on setting log level: %s", err))
 30	}
 31
 32	cfg := zap.Config{
 33		Level:            level,
 34		Encoding:         "console",
 35		OutputPaths:      outputs,
 36		ErrorOutputPaths: []string{"stderr"},
 37		EncoderConfig: zapcore.EncoderConfig{
 38			MessageKey: "message",
 39
 40			LevelKey:    "level",
 41			EncodeLevel: zapcore.CapitalColorLevelEncoder,
 42
 43			TimeKey: "timestamp",
 44			EncodeTime: func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {
 45				encoder.AppendString(ts.Local().Format(time.RFC3339))
 46			},
 47			EncodeDuration: zapcore.SecondsDurationEncoder,
 48
 49			CallerKey:    "caller",
 50			EncodeCaller: zapcore.ShortCallerEncoder,
 51
 52			// StacktraceKey: "stacktrace",
 53			StacktraceKey: "",
 54			LineEnding:    zapcore.DefaultLineEnding,
 55		},
 56	}
 57
 58	logger, err := cfg.Build()
 59	if err != nil {
 60		panic(err)
 61	}
 62	//nolint:errcheck
 63	defer logger.Sync()
 64	withOptions := logger.WithOptions(zap.AddCallerSkip(1))
 65	log = withOptions.Sugar()
 66}
 67
 68func sprintStackTrace(st []tracerr.Frame) string {
 69	builder := strings.Builder{}
 70	for _, f := range st {
 71		builder.WriteString(fmt.Sprintf("\n%s:%d %s()", f.Path, f.Line, f.Func))
 72	}
 73	builder.WriteString("\n")
 74	return builder.String()
 75}
 76
 77// appendStackTraceMaybeArgs will append the stacktrace to the args if one of them
 78// is a tracerr.Error
 79func appendStackTraceMaybeArgs(args []interface{}) []interface{} {
 80	for i := range args {
 81		if err, ok := args[i].(tracerr.Error); ok {
 82			st := err.StackTrace()
 83			return append(args, sprintStackTrace(st))
 84		}
 85	}
 86	return args
 87}
 88
 89// Debug calls log.Debug
 90func Debug(args ...interface{}) {
 91	log.Debug(args...)
 92}
 93
 94// Info calls log.Info
 95func Info(args ...interface{}) {
 96	log.Info(args...)
 97}
 98
 99// Warn calls log.Warn
100func Warn(args ...interface{}) {
101	args = appendStackTraceMaybeArgs(args)
102	log.Warn(args...)
103}
104
105// Error calls log.Error
106func Error(args ...interface{}) {
107	args = appendStackTraceMaybeArgs(args)
108	log.Error(args...)
109}
110
111// Fatal calls log.Fatal
112func Fatal(args ...interface{}) {
113	args = appendStackTraceMaybeArgs(args)
114	log.Fatal(args...)
115}
116
117// Debugf calls log.Debugf
118func Debugf(template string, args ...interface{}) {
119	log.Debugf(template, args...)
120}
121
122// Infof calls log.Infof
123func Infof(template string, args ...interface{}) {
124	log.Infof(template, args...)
125}
126
127// Warnf calls log.Warnf
128func Warnf(template string, args ...interface{}) {
129	log.Warnf(template, args...)
130}
131
132// Fatalf calls log.Warnf
133func Fatalf(template string, args ...interface{}) {
134	log.Fatalf(template, args...)
135}
136
137// Errorf calls log.Errorf and stores the error message into the ErrorFile
138func Errorf(template string, args ...interface{}) {
139	log.Errorf(template, args...)
140}
141
142// appendStackTraceMaybeKV will append the stacktrace to the KV if one of them
143// is a tracerr.Error
144func appendStackTraceMaybeKV(msg string, kv []interface{}) string {
145	for i := range kv {
146		if i%2 == 0 {
147			continue
148		}
149		if err, ok := kv[i].(tracerr.Error); ok {
150			st := err.StackTrace()
151			return fmt.Sprintf("%v: %v%v\n", msg, err, sprintStackTrace(st))
152		}
153	}
154	return msg
155}
156
157// Debugw calls log.Debugw
158func Debugw(template string, kv ...interface{}) {
159	log.Debugw(template, kv...)
160}
161
162// Infow calls log.Infow
163func Infow(template string, kv ...interface{}) {
164	log.Infow(template, kv...)
165}
166
167// Warnw calls log.Warnw
168func Warnw(template string, kv ...interface{}) {
169	template = appendStackTraceMaybeKV(template, kv)
170	log.Warnw(template, kv...)
171}
172
173// Errorw calls log.Errorw
174func Errorw(template string, kv ...interface{}) {
175	template = appendStackTraceMaybeKV(template, kv)
176	log.Errorw(template, kv...)
177}
178
179// Fatalw calls log.Fatalw
180func Fatalw(template string, kv ...interface{}) {
181	template = appendStackTraceMaybeKV(template, kv)
182	log.Fatalw(template, kv...)
183}