Skip to content

Commit

Permalink
remove debug and fatal levels. change attribute type to slog.Attr.
Browse files Browse the repository at this point in the history
  • Loading branch information
nasdf committed Mar 14, 2024
1 parent 2354e58 commit df37e3b
Show file tree
Hide file tree
Showing 11 changed files with 79 additions and 188 deletions.
19 changes: 11 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@ import "github.com/sourcenetwork/corelog"
var log = corelog.NewLogger("main")

func main() {
// with alternating key value pairs
log.Debug("message", "key", "val")

// with explicit attributes
log.Debug("message", corelog.String("key", "val"))
// with attributes
log.Info("message", corelog.String("key", "val"))

// with context
log.InfoContext(ctx, "message", corelog.Int("key", 10))

// with error stacktrace
log.ErrorE("message", err, corelog.Bool("key", true))

// with common attributes
attrs := log.WithAttrs(corelog.String("key", "val"))
attrs := log.WithAttrs(corelog.Float64("key", float64(1.234)))
attrs.Info("message")

// with common group
group := log.WithGroup("group")
group.Info("message", "key", "val")
group.Info("message", corelog.Any("key", struct{}{}))
}
```

Expand All @@ -34,7 +37,7 @@ Default config values can be set via environment variables.

| Env | Description | Values |
| ---------------- | ------------------------- | ----------------------------------- |
| `LOG_LEVEL` | sets logging level | `info` `debug` `error` `fatal` |
| `LOG_LEVEL` | sets logging level | `info` `error` |
| `LOG_FORMAT` | sets logging format | `json` `text` |
| `LOG_STACKTRACE` | enables stacktraces | `true` `false` |
| `LOG_SOURCE` | enables source location | `true` `false` |
Expand Down
4 changes: 0 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,10 @@ import (
)

const (
// LevelDebug specifies debug log level.
LevelDebug = "debug"
// LevelDebug specifies info log level.
LevelInfo = "info"
// LevelDebug specifies error log level.
LevelError = "error"
// LevelDebug specifies fatal log level.
LevelFatal = "fatal"
// FormatText specifies text output for a logger.
FormatText = "text"
// FormatJSON specifies json output for a logger.
Expand Down
4 changes: 2 additions & 2 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func TestDefaultConfigWithEnv(t *testing.T) {
}

func TestSetConfigOverrides(t *testing.T) {
SetConfigOverrides("net,level=debug,source=true,format=json,invalid;core,output=stdout,stacktrace=true")
SetConfigOverrides("net,level=error,source=true,format=json,invalid;core,output=stdout,stacktrace=true")

cfg := GetConfig("")
assert.Equal(t, "", cfg.Level)
Expand All @@ -34,7 +34,7 @@ func TestSetConfigOverrides(t *testing.T) {
assert.Equal(t, false, cfg.EnableSource)

net := GetConfig("net")
assert.Equal(t, LevelDebug, net.Level)
assert.Equal(t, LevelError, net.Level)
assert.Equal(t, "", net.Output)
assert.Equal(t, FormatJSON, net.Format)
assert.Equal(t, false, net.EnableStackTrace)
Expand Down
8 changes: 3 additions & 5 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ type namedHandler struct {
}

func (h namedHandler) Enabled(ctx context.Context, level slog.Level) bool {
leveler := namedLeveler(h.name)
return level >= leveler.Level()
return level >= namedLeveler(h.name).Level()
}

func (h namedHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
Expand All @@ -38,9 +37,8 @@ func (h namedHandler) Handle(ctx context.Context, record slog.Record) error {
config := GetConfig(h.name)
leveler := namedLeveler(h.name)
opts := &slog.HandlerOptions{
AddSource: config.EnableSource,
Level: leveler,
ReplaceAttr: leveler.ReplaceAttr,
AddSource: config.EnableSource,
Level: leveler,
}

var output io.Writer
Expand Down
32 changes: 4 additions & 28 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,44 +35,20 @@ func (h *TestHandler) WithGroup(name string) slog.Handler {
return &TestHandler{attrs: h.attrs, group: name, records: h.records}
}

func TestHandlerWithLevelDebug(t *testing.T) {
SetConfig(Config{Level: LevelDebug})
handler := namedHandler{name: "test"}

assert.True(t, handler.Enabled(context.Background(), levelDebug))
assert.True(t, handler.Enabled(context.Background(), levelInfo))
assert.True(t, handler.Enabled(context.Background(), levelError))
assert.True(t, handler.Enabled(context.Background(), levelFatal))
}

func TestHandlerWithLevelInfo(t *testing.T) {
SetConfig(Config{Level: LevelInfo})
handler := namedHandler{name: "test"}

assert.False(t, handler.Enabled(context.Background(), levelDebug))
assert.True(t, handler.Enabled(context.Background(), levelInfo))
assert.True(t, handler.Enabled(context.Background(), levelError))
assert.True(t, handler.Enabled(context.Background(), levelFatal))
assert.True(t, handler.Enabled(context.Background(), slog.LevelInfo))
assert.True(t, handler.Enabled(context.Background(), slog.LevelError))
}

func TestHandlerWithLevelError(t *testing.T) {
SetConfig(Config{Level: LevelError})
handler := namedHandler{name: "test"}

assert.False(t, handler.Enabled(context.Background(), levelDebug))
assert.False(t, handler.Enabled(context.Background(), levelInfo))
assert.True(t, handler.Enabled(context.Background(), levelError))
assert.True(t, handler.Enabled(context.Background(), levelFatal))
}

func TestHandlerWithLevelFatal(t *testing.T) {
SetConfig(Config{Level: LevelFatal})
handler := namedHandler{name: "test"}

assert.False(t, handler.Enabled(context.Background(), levelDebug))
assert.False(t, handler.Enabled(context.Background(), levelInfo))
assert.False(t, handler.Enabled(context.Background(), levelError))
assert.True(t, handler.Enabled(context.Background(), levelFatal))
assert.False(t, handler.Enabled(context.Background(), slog.LevelInfo))
assert.True(t, handler.Enabled(context.Background(), slog.LevelError))
}

func TestHandlerWithAttrs(t *testing.T) {
Expand Down
45 changes: 0 additions & 45 deletions level.go

This file was deleted.

40 changes: 0 additions & 40 deletions level_test.go

This file was deleted.

19 changes: 19 additions & 0 deletions leveler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package corelog

import "log/slog"

// namedLeveler is an slog.Leveler that gets its value from a named config.
type namedLeveler string

func (n namedLeveler) Level() slog.Level {
switch cfg := GetConfig(string(n)); cfg.Level {
case LevelInfo:
return slog.LevelInfo
case LevelError:
return slog.LevelError
default:
// default to info if no value is set
// or the set value is invalid
return slog.LevelInfo
}
}
19 changes: 19 additions & 0 deletions leveler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package corelog

import (
"log/slog"
"testing"

"github.com/stretchr/testify/assert"
)

func TestNamedLeveler(t *testing.T) {
leveler := namedLeveler("core")
assert.Equal(t, slog.LevelInfo, leveler.Level())

SetConfigOverride("core", Config{Level: LevelInfo})
assert.Equal(t, slog.LevelInfo, leveler.Level())

SetConfigOverride("core", Config{Level: LevelError})
assert.Equal(t, slog.LevelError, leveler.Level())
}
67 changes: 16 additions & 51 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"log/slog"
"os"
"runtime"
"time"
)
Expand Down Expand Up @@ -41,73 +40,39 @@ func (l *Logger) WithGroup(name string) *Logger {
}
}

// Debug logs a message at debug log level.
func (l *Logger) Debug(msg string, args ...any) {
l.log(context.Background(), levelDebug, nil, msg, args)
// Info logs a message at info log level.
func (l *Logger) Info(msg string, args ...slog.Attr) {
l.log(context.Background(), slog.LevelInfo, nil, msg, args)
}

// Info logs a message at info log level.
func (l *Logger) Info(msg string, args ...any) {
l.log(context.Background(), levelInfo, nil, msg, args)
// InfoContext logs a message at info log level.
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...slog.Attr) {
l.log(ctx, slog.LevelInfo, nil, msg, args)
}

// Error logs a message at error log level.
func (l *Logger) Error(msg string, args ...any) {
l.log(context.Background(), levelError, nil, msg, args)
func (l *Logger) Error(msg string, args ...slog.Attr) {
l.log(context.Background(), slog.LevelError, nil, msg, args)
}

// ErrorE logs a message at error log level with an error stacktrace.
func (l *Logger) ErrorE(msg string, err error, args ...any) {
l.log(context.Background(), levelError, err, msg, args)
}

// Fatal logs a message at fatal log level.
func (l *Logger) Fatal(msg string, args ...any) {
l.log(context.Background(), levelFatal, nil, msg, args)
os.Exit(1)
}

// FatalE logs a message at fatal log level with an error stacktrace.
func (l *Logger) FatalE(msg string, err error, args ...any) {
l.log(context.Background(), levelFatal, err, msg, args)
os.Exit(1)
}

// DebugContext logs a message at debug log level.
func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, levelDebug, nil, msg, args)
}

// InfoContext logs a message at info log level.
func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, levelInfo, nil, msg, args)
func (l *Logger) ErrorE(msg string, err error, args ...slog.Attr) {
l.log(context.Background(), slog.LevelError, err, msg, args)
}

// ErrorContext logs a message at error log level.
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, levelError, nil, msg, args)
func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...slog.Attr) {
l.log(ctx, slog.LevelError, nil, msg, args)
}

// ErrorContextE logs a message at error log level with an error stacktrace.
func (l *Logger) ErrorContextE(ctx context.Context, msg string, err error, args ...any) {
l.log(ctx, levelError, err, msg, args)
}

// FatalContext logs a message at fatal log level and calls os.Exit(1).
func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any) {
l.log(ctx, levelFatal, nil, msg, args)
os.Exit(1)
}

// FatalContextE logs a message at fatal log level with an error stacktrace and calls os.Exit(1).
func (l *Logger) FatalContextE(ctx context.Context, msg string, err error, args ...any) {
l.log(ctx, levelFatal, err, msg, args)
os.Exit(1)
func (l *Logger) ErrorContextE(ctx context.Context, msg string, err error, args ...slog.Attr) {
l.log(ctx, slog.LevelError, err, msg, args)
}

// log wraps calls to the underlying logger so that the caller source can be corrected and
// an optional stacktrace can be included.
func (l *Logger) log(ctx context.Context, level slog.Level, err error, msg string, args []any) {
func (l *Logger) log(ctx context.Context, level slog.Level, err error, msg string, args []slog.Attr) {
// check if logger is enabled
if !l.handler.Enabled(ctx, level) {
return
Expand All @@ -124,7 +89,7 @@ func (l *Logger) log(ctx context.Context, level slog.Level, err error, msg strin

r := slog.NewRecord(time.Now(), level, msg, pcs[0])
r.Add(slog.Any("name", l.name))
r.Add(args...)
r.AddAttrs(args...)

// add stack trace if enabled
if err != nil && config.EnableStackTrace {
Expand Down
Loading

0 comments on commit df37e3b

Please sign in to comment.