github.com/icexin/eggos@v0.4.2-0.20220216025428-78b167e4f349/log/log.go (about)

     1  package log
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/icexin/eggos/console"
     9  	"github.com/icexin/eggos/drivers/uart"
    10  	"github.com/icexin/eggos/kernel/sys"
    11  )
    12  
    13  type LogLevel int8
    14  
    15  const (
    16  	LoglvlDebug LogLevel = iota
    17  	LoglvlInfo
    18  	LoglvlWarn
    19  	LoglvlError
    20  	LoglvlNone
    21  )
    22  
    23  const (
    24  	loglvlEnv      = "EGGOS_LOGLVL"
    25  	loglvlEnvDebug = "debug"
    26  	loglvlEnvInfo  = "info"
    27  	loglvlEnvWarn  = "warn"
    28  	loglvlEnvError = "error"
    29  	loglvlEnvNone  = "none"
    30  
    31  	defaultLoglvl = LoglvlError
    32  )
    33  
    34  var (
    35  	Level LogLevel
    36  
    37  	ErrInvalidLogLevel = fmt.Errorf("invalid log level")
    38  )
    39  
    40  func init() {
    41  	lvl := os.Getenv("EGGOS_LOGLVL")
    42  	switch lvl {
    43  	case loglvlEnvDebug:
    44  		Level = LoglvlDebug
    45  	case loglvlEnvInfo:
    46  		Level = LoglvlInfo
    47  	case loglvlEnvWarn:
    48  		Level = LoglvlWarn
    49  	case loglvlEnvError:
    50  		Level = LoglvlError
    51  	default:
    52  		Level = defaultLoglvl
    53  	}
    54  }
    55  
    56  func SetLevel(l LogLevel) error {
    57  	if l < LoglvlDebug || l > LoglvlNone {
    58  		return ErrInvalidLogLevel
    59  	}
    60  
    61  	Level = l
    62  
    63  	return nil
    64  }
    65  
    66  func logf(lvl LogLevel, fmtstr string, args ...interface{}) {
    67  	if lvl < Level {
    68  		return
    69  	}
    70  
    71  	buf := bytes.Buffer{}
    72  	fmt.Fprintf(&buf, fmtstr, args...)
    73  	buf.WriteByte('\n')
    74  	buf.WriteTo(console.Console())
    75  }
    76  
    77  func Debugf(fmtstr string, args ...interface{}) {
    78  	logf(LoglvlDebug, fmtstr, args...)
    79  }
    80  
    81  func Infof(fmtstr string, args ...interface{}) {
    82  	logf(LoglvlInfo, fmtstr, args...)
    83  }
    84  
    85  func Warnf(fmtstr string, args ...interface{}) {
    86  	logf(LoglvlWarn, fmtstr, args...)
    87  }
    88  
    89  func Errorf(fmtstr string, args ...interface{}) {
    90  	logf(LoglvlError, fmtstr, args...)
    91  }
    92  
    93  //go:nosplit
    94  func PrintStr(s string) {
    95  	uart.WriteString(s)
    96  }
    97  
    98  const hextab = "0123456789abcdef"
    99  
   100  //go:nosplit
   101  func PrintHex(n uintptr) {
   102  	shift := sys.PtrSize*8 - 4
   103  	for ; shift > 0; shift = shift - 4 {
   104  		v := (n >> shift) & 0x0F
   105  		ch := hextab[v]
   106  		uart.WriteByte(ch)
   107  	}
   108  	uart.WriteByte(hextab[n&0x0F])
   109  }