64 lines
1.2 KiB
Go
64 lines
1.2 KiB
Go
package logger
|
|
|
|
import (
|
|
"context"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
const contextKey = "logger"
|
|
|
|
type Interface interface {
|
|
Info(format string, args ...interface{})
|
|
Error(format string, args ...interface{})
|
|
Debug(format string, args ...interface{})
|
|
Warn(format string, args ...interface{})
|
|
GetLevel() log.Level
|
|
}
|
|
|
|
type Logger struct {
|
|
logger *log.Logger
|
|
}
|
|
|
|
func FromContext(ctx context.Context) Interface {
|
|
logger, ok := ctx.Value(contextKey).(*Logger)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
|
|
return logger
|
|
}
|
|
|
|
func NewLogger(level log.Level) Interface {
|
|
l := log.New()
|
|
l.SetFormatter(&log.JSONFormatter{})
|
|
l.SetLevel(level)
|
|
|
|
return &Logger{
|
|
logger: l,
|
|
}
|
|
}
|
|
|
|
func NewContext(ctx context.Context, logger Interface) context.Context {
|
|
return context.WithValue(ctx, contextKey, logger)
|
|
}
|
|
|
|
func (l *Logger) Info(format string, args ...interface{}) {
|
|
l.logger.Infof(format, args...)
|
|
}
|
|
|
|
func (l *Logger) Error(format string, args ...interface{}) {
|
|
l.logger.Errorf(format, args...)
|
|
}
|
|
|
|
func (l *Logger) Debug(format string, args ...interface{}) {
|
|
l.logger.Debugf(format, args...)
|
|
}
|
|
|
|
func (l *Logger) Warn(format string, args ...interface{}) {
|
|
l.logger.Warnf(format, args...)
|
|
}
|
|
|
|
func (l *Logger) GetLevel() log.Level {
|
|
return l.logger.GetLevel()
|
|
}
|