Skip to content

Commit

Permalink
Add leveled logging (#1249)
Browse files Browse the repository at this point in the history
Co-authored-by: Ibrahim Jarif <ibrahim@dgraph.io>
  • Loading branch information
vardhanapoorv and Ibrahim Jarif authored Apr 13, 2020
1 parent 30eeec2 commit 4f6763c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
30 changes: 25 additions & 5 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,24 +62,44 @@ func (opt *Options) Debugf(format string, v ...interface{}) {
opt.Logger.Debugf(format, v...)
}

type loggingLevel int

const (
DEBUG loggingLevel = iota
INFO
WARNING
ERROR
)

type defaultLog struct {
*log.Logger
level loggingLevel
}

var defaultLogger = &defaultLog{Logger: log.New(os.Stderr, "badger ", log.LstdFlags)}
func defaultLogger(level loggingLevel) *defaultLog {
return &defaultLog{Logger: log.New(os.Stderr, "badger ", log.LstdFlags), level: level}
}

func (l *defaultLog) Errorf(f string, v ...interface{}) {
l.Printf("ERROR: "+f, v...)
if l.level <= ERROR {
l.Printf("ERROR: "+f, v...)
}
}

func (l *defaultLog) Warningf(f string, v ...interface{}) {
l.Printf("WARNING: "+f, v...)
if l.level <= WARNING {
l.Printf("WARNING: "+f, v...)
}
}

func (l *defaultLog) Infof(f string, v ...interface{}) {
l.Printf("INFO: "+f, v...)
if l.level <= INFO {
l.Printf("INFO: "+f, v...)
}
}

func (l *defaultLog) Debugf(f string, v ...interface{}) {
l.Printf("DEBUG: "+f, v...)
if l.level <= DEBUG {
l.Printf("DEBUG: "+f, v...)
}
}
13 changes: 12 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func DefaultOptions(path string) Options {
ValueLogMaxEntries: 1000000,
ValueThreshold: 32,
Truncate: false,
Logger: defaultLogger,
Logger: defaultLogger(INFO),
LogRotatesToFlush: 2,
EventLogging: false,
EncryptionKey: []byte{},
Expand Down Expand Up @@ -217,6 +217,17 @@ func (opt Options) WithValueDir(val string) Options {
return opt
}

// WithLoggingLevel returns a new Options value with logging level of the
// default logger set to the given value.
// LoggingLevel sets the level of logging. It should be one of DEBUG, INFO,
// WARNING or ERROR levels.
//
// The default value of LoggingLevel is INFO.
func (opt Options) WithLoggingLevel(val loggingLevel) Options {
opt.Logger = defaultLogger(val)
return opt
}

// WithSyncWrites returns a new Options value with SyncWrites set to the given value.
//
// When SyncWrites is true all writes are synced to disk. Setting this to false would achieve better
Expand Down

0 comments on commit 4f6763c

Please sign in to comment.