Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active April 14, 2026 08:08
Show Gist options
  • Select an option

  • Save alexedwards/475827e068b8b2837f8ec69d150de990 to your computer and use it in GitHub Desktop.

Select an option

Save alexedwards/475827e068b8b2837f8ec69d150de990 to your computer and use it in GitHub Desktop.
Levelled and structure logger using log package only
package logger
import (
"fmt"
"log"
"os"
"strings"
)
type Level int
const (
DEBUG Level = iota
INFO
WARN
ERROR
)
type Logger struct {
inner *log.Logger
level Level
}
func New(level Level) *Logger {
return &Logger{log.New(os.Stderr, "", log.Ldate|log.Ltime), level}
}
func (l *Logger) log(level Level, label, msg string, kvs []any) {
if level < l.level {
return
}
parts := make([]string, 0, len(kvs)/2)
for i := 0; i+1 < len(kvs); i += 2 {
parts = append(parts, fmt.Sprintf("%v=%v", kvs[i], kvs[i+1]))
}
line := fmt.Sprintf("[%s] %s", label, msg)
if len(parts) > 0 {
line += " " + strings.Join(parts, " ")
}
l.inner.Output(3, line)
}
func (l *Logger) Debug(msg string, kvs ...any) { l.log(DEBUG, "DEBUG", msg, kvs) }
func (l *Logger) Info(msg string, kvs ...any) { l.log(INFO, "INFO", msg, kvs) }
func (l *Logger) Warn(msg string, kvs ...any) { l.log(WARN, "WARN", msg, kvs) }
func (l *Logger) Error(msg string, kvs ...any) { l.log(ERROR, "ERROR", msg, kvs) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment