1
0
Fork 0
gobelt/log/log.go

78 lines
2.0 KiB
Go
Raw Normal View History

2018-06-24 00:11:53 +00:00
package log
import (
2018-06-24 00:57:14 +00:00
"context"
2018-06-24 00:11:53 +00:00
"github.com/lytics/logrus"
)
// Logger is a Logrus logger used by the package.
var Logger *logrus.Logger
// F is a short alias for a string to interface map.
type F map[string]interface{}
func init() {
Logger = logrus.New()
}
// Debug prints a debug message with given fields attached.
2018-06-24 00:57:14 +00:00
func Debug(ctx context.Context, msg string, fields ...F) {
withFields(mergeFields(ctx, fields)).Debug(msg)
2018-06-24 00:11:53 +00:00
}
// Debugf prints a formatted debug message.
2018-06-24 00:57:14 +00:00
func Debugf(ctx context.Context, format string, args ...interface{}) {
withFields(contextFields(ctx)).Debugf(format, args...)
2018-06-24 00:11:53 +00:00
}
// Info prints an info message with given fields attached.
2018-06-24 00:57:14 +00:00
func Info(ctx context.Context, msg string, fields ...F) {
withFields(mergeFields(ctx, fields)).Info(msg)
2018-06-24 00:11:53 +00:00
}
// Infof prints a formatted info message.
2018-06-24 00:57:14 +00:00
func Infof(ctx context.Context, format string, args ...interface{}) {
withFields(contextFields(ctx)).Infof(format, args...)
2018-06-24 00:11:53 +00:00
}
// Error prints an error message with given fields attached.
2018-06-24 00:57:14 +00:00
func Error(ctx context.Context, msg string, fields ...F) {
withFields(mergeFields(ctx, fields)).Error(msg)
2018-06-24 00:11:53 +00:00
}
// Errorf prints a formatted error message.
2018-06-24 00:57:14 +00:00
func Errorf(ctx context.Context, format string, args ...interface{}) {
withFields(contextFields(ctx)).Errorf(format, args...)
2018-06-24 00:11:53 +00:00
}
// Fatal prints an error message with given fields attached and then exits.
2018-06-24 00:57:14 +00:00
func Fatal(ctx context.Context, msg string, fields ...F) {
withFields(mergeFields(ctx, fields)).Fatal(msg)
2018-06-24 00:11:53 +00:00
}
// Fatalf prints a formatted error message and then exits.
2018-06-24 00:57:14 +00:00
func Fatalf(ctx context.Context, format string, args ...interface{}) {
withFields(contextFields(ctx)).Fatalf(format, args...)
2018-06-24 00:11:53 +00:00
}
2018-06-24 00:57:14 +00:00
func mergeFields(ctx context.Context, fields []F) F {
ctxf := contextFields(ctx)
if len(ctxf) == 0 && len(fields) == 0 {
return nil
}
for i := 0; i < len(fields); i++ {
for k, v := range fields[i] {
ctxf[k] = v
2018-06-24 00:11:53 +00:00
}
}
2018-06-24 00:57:14 +00:00
return ctxf
}
func withFields(f F) *logrus.Entry {
if len(f) == 0 {
return logrus.NewEntry(Logger)
}
2018-06-24 01:06:28 +00:00
return Logger.WithFields(logrus.Fields(f))
2018-06-24 00:11:53 +00:00
}