Skip to content

Commit

Permalink
levellog: dirt-simple leveled text logger
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Koch <[email protected]>
  • Loading branch information
hugelgupf committed Feb 4, 2024
1 parent 168c06d commit e47792b
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions llog/levellog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2024 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// llog is a dirt-simple leveled text logger.
package llog

import (
"log"
"log/slog"
"math"
"testing"
)

// Log is the stdlib default log sink.
var Default *Logger = &Logger{Sink: log.Printf}

// Null is a logger that prints nothing.
var Null *Logger = &Logger{Sink: nil}

// Test is a logger that prints every level to t.Logf.
func Test(t testing.TB) *Logger {
return &Logger{Sink: t.Logf, Level: slog.Level(math.MinInt32)}
}

// Debug prints to log.Printf at the debug level.
var Debug *Logger = &Logger{Sink: log.Printf, Level: slog.LevelDebug}

// Printf is a logger printf function.
type Printf func(format string, v ...any)

// Logger is a dirt-simple leveled logger.
//
// If the log level is >= Level, it logs to the given Sink.
//
// Logger and Sink may be nil in order to log nothing.
type Logger struct {
Sink Printf
Level slog.Level
}

// Printf returns a Printf that can be passed around to log at the given level.
func (l *Logger) Printf(level slog.Level) Printf {
return func(fmt string, args ...any) {
if l == nil {
return
}
l.Logf(level, fmt, args...)
}
}

// Debugf is a printf function that logs at the Debug level.
func (l *Logger) Debugf(fmt string, args ...any) {
if l == nil {
return
}
l.Logf(slog.LevelDebug, fmt, args...)
}

// Infof is a printf function that logs at the Info level.
func (l *Logger) Infof(fmt string, args ...any) {
if l == nil {
return
}
l.Logf(slog.LevelInfo, fmt, args...)
}

// Warnf is a printf function that logs at the Warn level.
func (l *Logger) Warnf(fmt string, args ...any) {
if l == nil {
return
}
l.Logf(slog.LevelWarn, fmt, args...)
}

// Errorf is a printf function that logs at the Error level.
func (l *Logger) Errorf(fmt string, args ...any) {
if l == nil {
return
}
l.Logf(slog.LevelError, fmt, args...)
}

// Logf logs at the given level.
func (l *Logger) Logf(level slog.Level, fmt string, args ...any) {
if l == nil || l.Sink == nil {
return
}
if level >= l.Level {
l.Sink(fmt, args...)
}
}

0 comments on commit e47792b

Please sign in to comment.