logger.go raw

   1  /*
   2   * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
   3   * SPDX-License-Identifier: Apache-2.0
   4   */
   5  
   6  package badger
   7  
   8  import (
   9  	"log"
  10  	"os"
  11  )
  12  
  13  // Logger is implemented by any logging system that is used for standard logs.
  14  type Logger interface {
  15  	Errorf(string, ...interface{})
  16  	Warningf(string, ...interface{})
  17  	Infof(string, ...interface{})
  18  	Debugf(string, ...interface{})
  19  }
  20  
  21  // Errorf logs an ERROR log message to the logger specified in opts or to the
  22  // global logger if no logger is specified in opts.
  23  func (opt *Options) Errorf(format string, v ...interface{}) {
  24  	if opt.Logger == nil {
  25  		return
  26  	}
  27  	opt.Logger.Errorf(format, v...)
  28  }
  29  
  30  // Infof logs an INFO message to the logger specified in opts.
  31  func (opt *Options) Infof(format string, v ...interface{}) {
  32  	if opt.Logger == nil {
  33  		return
  34  	}
  35  	opt.Logger.Infof(format, v...)
  36  }
  37  
  38  // Warningf logs a WARNING message to the logger specified in opts.
  39  func (opt *Options) Warningf(format string, v ...interface{}) {
  40  	if opt.Logger == nil {
  41  		return
  42  	}
  43  	opt.Logger.Warningf(format, v...)
  44  }
  45  
  46  // Debugf logs a DEBUG message to the logger specified in opts.
  47  func (opt *Options) Debugf(format string, v ...interface{}) {
  48  	if opt.Logger == nil {
  49  		return
  50  	}
  51  	opt.Logger.Debugf(format, v...)
  52  }
  53  
  54  type loggingLevel int
  55  
  56  const (
  57  	DEBUG loggingLevel = iota
  58  	INFO
  59  	WARNING
  60  	ERROR
  61  )
  62  
  63  type defaultLog struct {
  64  	*log.Logger
  65  	level loggingLevel
  66  }
  67  
  68  func defaultLogger(level loggingLevel) *defaultLog {
  69  	return &defaultLog{Logger: log.New(os.Stderr, "badger ", log.LstdFlags), level: level}
  70  }
  71  
  72  func (l *defaultLog) Errorf(f string, v ...interface{}) {
  73  	if l.level <= ERROR {
  74  		l.Printf("ERROR: "+f, v...)
  75  	}
  76  }
  77  
  78  func (l *defaultLog) Warningf(f string, v ...interface{}) {
  79  	if l.level <= WARNING {
  80  		l.Printf("WARNING: "+f, v...)
  81  	}
  82  }
  83  
  84  func (l *defaultLog) Infof(f string, v ...interface{}) {
  85  	if l.level <= INFO {
  86  		l.Printf("INFO: "+f, v...)
  87  	}
  88  }
  89  
  90  func (l *defaultLog) Debugf(f string, v ...interface{}) {
  91  	if l.level <= DEBUG {
  92  		l.Printf("DEBUG: "+f, v...)
  93  	}
  94  }
  95