Skip to content

Commit

Permalink
internal/witcli, wit/logging: add basic Logger type
Browse files Browse the repository at this point in the history
  • Loading branch information
ydnar committed Oct 30, 2024
1 parent 8e1bacc commit 91685e5
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 0 deletions.
18 changes: 18 additions & 0 deletions internal/witcli/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package witcli

import (
"os"

"github.com/bytecodealliance/wasm-tools-go/wit/logging"
)

// Logger returns a [logging.Logger] that outputs to stdout.
func Logger(verbose, debug bool) logging.Logger {
level := logging.LevelWarn
if debug {
level = logging.LevelDebug
} else if verbose {
level = logging.LevelInfo
}
return logging.NewLogger(os.Stderr, level)
}
91 changes: 91 additions & 0 deletions wit/logging/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package logging

import (
"io"
"log"
"math"
)

// Level represents a logging level, identical to [slog.Level].
type Level int

const (
LevelDebug Level = -4
LevelInfo Level = 0
LevelWarn Level = 4
LevelError Level = 8
LevelNever Level = math.MaxInt
)

// Logger represents a simple logging interface.
type Logger interface {
// Level returns the current logging level for this Logger.
Level() Level

// Logf logs a message with a logging level.
Logf(level Level, format string, v ...any)

// Debugf logs a message with level debug.
Debugf(format string, v ...any)

// Infof logs a message with level info.
Infof(format string, v ...any)

// Printf is an alias for Infof.
Printf(format string, v ...any)

// Warnf logs a message with level warn.
Warnf(format string, v ...any)

// Errorf logs a message with level error.
Errorf(format string, v ...any)
}

// DiscardLogger returns a logger that discards all output.
func DiscardLogger() Logger {
return &logger{level: LevelNever}
}

// NewLogger returns a new leveled logger that writes to out.
func NewLogger(out io.Writer, level Level) Logger {
return &logger{
level: level,
logger: log.New(out, "", 0),
}
}

type logger struct {
level Level
logger *log.Logger
}

func (l *logger) Level() Level {
return l.level
}

func (l *logger) Logf(level Level, format string, v ...any) {
if l.level > level || l.logger == nil {
return
}
l.logger.Printf(format, v...)
}

func (l *logger) Debugf(format string, v ...any) {
l.Logf(LevelDebug, format, v...)
}

func (l *logger) Infof(format string, v ...any) {
l.Logf(LevelInfo, format, v...)
}

func (l *logger) Printf(format string, v ...any) {
l.Logf(LevelInfo, format, v...)
}

func (l *logger) Warnf(format string, v ...any) {
l.Logf(LevelWarn, format, v...)
}

func (l *logger) Errorf(format string, v ...any) {
l.Logf(LevelError, format, v...)
}

0 comments on commit 91685e5

Please sign in to comment.