src.dualinventive.com/go/lib/dilog/logrus.go

49 lines
1.3 KiB
Go

package dilog
import (
"fmt"
"io"
"os"
"github.com/sirupsen/logrus"
)
// Logrus is the wrapper around github.com/sirupsen/logrus for Logger-interface compliance
type Logrus struct {
*logrus.Entry
}
// WithField adds one field to the logger
func (l *Logrus) WithField(key string, value interface{}) Logger {
return &Logrus{l.Entry.WithField(key, value)}
}
// WithFields adds multiple fields to the logger
func (l *Logrus) WithFields(fields Fields) Logger {
return &Logrus{l.Entry.WithFields(fields)}
}
// WithError adds an error to the logger
func (l *Logrus) WithError(err error) Logger {
return &Logrus{l.Entry.WithError(err)}
}
// NewLogger returns a new logger and sets the logfile and loglevel
func NewLogger(logfile, loglevel string) (Logger, error) {
var writer io.Writer = os.Stdout
if logfile != "" {
var err error
// #nosec ignore too wide file permissions
if writer, err = os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666); err != nil {
return nil, fmt.Errorf("error opening log file: %v", err)
}
}
logrus.SetOutput(writer)
level, err := logrus.ParseLevel(loglevel)
if err != nil {
return nil, fmt.Errorf("invalid log level: %v", err)
}
logrus.SetLevel(level)
return &Logrus{logrus.NewEntry(logrus.StandardLogger())}, nil
}