Skip to content

Commit

Permalink
fix the usages of Set/WithXXX
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Oct 19, 2024
1 parent 6f9e098 commit e51f96b
Show file tree
Hide file tree
Showing 9 changed files with 109 additions and 36 deletions.
4 changes: 2 additions & 2 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//
// import "github.com/hedzr/logg/slog"
//
// var logger = slog.New("my-app").WithLevel(slog.Debug).WithJSONMode()
// var logger = slog.New("my-app").SetLevel(slog.Debug).SetJSONMode()
// logger.Info("info message here", "attr1", 3, "attr2", false, "attr3", "text details")
// logger.Println() // just an empty line
// logger.Println("text message", attrs...)
Expand All @@ -25,7 +25,7 @@
// logger.Fail("fail message", attrs...)
// logger.Verbose("verbose message", attrs...) // only work for build tag 'verbose' defined
//
// var subl = logger.New("child1").With(attrs...)
// var subl = logger.New("child1").Set(attrs...)
// subl.Debug("debug")
//
// For more detail, please take a look at:
Expand Down
4 changes: 2 additions & 2 deletions slog/adapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ func NewSlogHandler(logger Logger, config *HandlerOptions) logslog.Handler {
}

if config.Level != PanicLevel {
logger.WithLevel(config.Level)
logger.SetLevel(config.Level)
}

return &handler4LogSlog{logger.WithColorMode(!config.NoColor).WithJSONMode(config.JSON)}
return &handler4LogSlog{logger.SetColorMode(!config.NoColor).SetJSONMode(config.JSON)}
}

// HandlerOptions is used for our log/slog Handler.
Expand Down
17 changes: 10 additions & 7 deletions slog/adapters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,11 @@ func TestHandler4LogSlog_Enabled(t *testing.T) { //nolint:revive
{FailLevel, logslog.LevelInfo, true},
{MaxLevel, logslog.LevelInfo, true},

{PanicLevel, logslog.LevelDebug, false},
{FatalLevel, logslog.LevelDebug, false},
{ErrorLevel, logslog.LevelDebug, false},
{WarnLevel, logslog.LevelDebug, false},
{InfoLevel, logslog.LevelDebug, false},
{PanicLevel, logslog.LevelDebug, true},
{FatalLevel, logslog.LevelDebug, true},
{ErrorLevel, logslog.LevelDebug, true},
{WarnLevel, logslog.LevelDebug, true},
{InfoLevel, logslog.LevelDebug, true},
{DebugLevel, logslog.LevelDebug, true},
{TraceLevel, logslog.LevelDebug, true},

Expand All @@ -180,8 +180,11 @@ func TestHandler4LogSlog_Enabled(t *testing.T) { //nolint:revive
{FailLevel, logslog.LevelDebug, true},
{MaxLevel, logslog.LevelDebug, true},
} {
if ll, ok := l.(interface{ WithLevel(l Level) *Entry }); ok {
ll.WithLevel(c.holding)
// 1. hold OffLevel: any request levels are denied
// 2. hold AlwaysLevel: any request levels are allowed
// 3. in testing/debugging mode, requesting DebugLevel are always allowed.
if ll, ok := l.(interface{ SetLevel(l Level) *Entry }); ok {
ll.SetLevel(c.holding)
}
if actual := h.Enabled(ctx, c.requesting); actual != c.expect {
t.Fatalf("%5d. h[%v].Enable(ctx, %v) => expect %v, but got %v, FAILED!", i+1, l.Level(), c.requesting, c.expect, actual)
Expand Down
73 changes: 60 additions & 13 deletions slog/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (s *Entry) String() string {

func WithJSONMode(b ...bool) Opt {
return func(s *Entry) {
s.WithJSONMode(b...)
s.SetJSONMode(b...)
}
}

Expand All @@ -201,7 +201,7 @@ func (s *Entry) WithJSONMode(b ...bool) *Entry {

func WithColorMode(b ...bool) Opt {
return func(s *Entry) {
s.WithColorMode(b...)
s.SetColorMode(b...)
}
}

Expand All @@ -225,7 +225,7 @@ func (s *Entry) WithColorMode(b ...bool) *Entry {

func WithUTCMode(b ...bool) Opt {
return func(s *Entry) {
s.WithUTCMode(b...)
s.SetUTCMode(b...)
}
}

Expand All @@ -250,7 +250,7 @@ func (s *Entry) WithUTCMode(b ...bool) *Entry {

func WithTimeFormat(layout ...string) Opt {
return func(s *Entry) {
s.WithTimeFormat(layout...)
s.SetTimeFormat(layout...)
}
}

Expand All @@ -273,7 +273,7 @@ func (s *Entry) WithTimeFormat(layout ...string) *Entry {

func WithLevel(lvl Level) Opt {
return func(s *Entry) {
s.WithLevel(lvl)
s.SetLevel(lvl)
}
}

Expand Down Expand Up @@ -326,7 +326,7 @@ func (s *Entry) Level() (lvl Level) {
// instead.
func WithAttrs(attrs ...Attr) Opt {
return func(s *Entry) {
s.WithAttrs(attrs...)
s.SetAttrs(attrs...)
}
}

Expand Down Expand Up @@ -362,14 +362,18 @@ func (s *Entry) WithAttrs(attrs ...Attr) *Entry {

// WithAttrs1 allows an Attrs passed into New. Sample is:
//
// lc1 := l.New("c1").WithAttrs1(NewAttrs("a1", 1, "a2", 2.7, NewAttr("a3", "string")))
// lc1 := l.New("c1", WithAttrs1(NewAttrs("a1", 1, "a2", 2.7, NewAttr("a3", "string"))))
//
// Package level WitAttrs1 can be passed into l.New(...). It takes
// effects into the logger right here. But l.WithXXX() will make a
// new child logger instance.
//
// NewAttrs receives a freeform args list.
//
// You can use With(...) to simplify WithAttrs1+NewAttrs1 calling.
// You can also use With(...) to simplify WithAttrs1+NewAttrs1 calling.
func WithAttrs1(attrs Attrs) Opt {
return func(s *Entry) {
s.WithAttrs1(attrs)
s.SetAttrs1(attrs)
}
}

Expand Down Expand Up @@ -398,7 +402,7 @@ func (s *Entry) WithAttrs1(attrs Attrs) *Entry {
// More samples can be found at New.
func With(args ...any) Opt {
return func(s *Entry) {
s.With(args...)
s.Set(args...)
}
}

Expand Down Expand Up @@ -454,7 +458,7 @@ func (s *Entry) GetWriterBy(level Level) (wr LogWriter) {
// For each child loggers, uses their method [Entry.WithWriter],
func WithWriter(wr io.Writer) Opt {
return func(s *Entry) {
s.WithWriter(wr)
s.SetWriter(wr)
}
}

Expand Down Expand Up @@ -494,7 +498,7 @@ func (s *Entry) AddWriter(wr io.Writer) *Entry {

func WithErrorWriter(wr io.Writer) Opt {
return func(s *Entry) {
s.WithWriter(wr)
s.SetErrorWriter(wr)
}
}

Expand Down Expand Up @@ -793,13 +797,56 @@ func (s *Entry) LogAttrs(ctx context.Context, level Level, msg string, args ...a
}

// Log implements Logger.
func (s *Entry) Log(ctx context.Context, level Level, msg string, args ...any) {
func (s *Entry) Logit(ctx context.Context, level Level, msg string, args ...any) {
if s.EnabledContext(ctx, level) {
pc := getpc(2, s.extraFrames)
s.logContext(ctx, level, pc, msg, args...)
}
}

func (s *Entry) Log(ctx context.Context, level logslog.Level, msg string, args ...any) {
lvl := logsloglevel2Level(level)
if s.EnabledContext(ctx, lvl) {
pc := getpc(2, s.extraFrames)
s.logContext(ctx, lvl, pc, msg, args...)
}
}

const (
LevelVerbose = logslog.Level(-16)
LevelTrace = logslog.Level(-8)
LevelNotice = logslog.Level(2)
LevelHint = logslog.Level(3)
LevelFatal = logslog.Level(16)
LevelPanic = logslog.Level(17)
)

func logsloglevel2Level(level logslog.Level) Level {
switch level {
case logslog.LevelDebug:
return DebugLevel
case logslog.LevelInfo:
return InfoLevel
case logslog.LevelWarn:
return WarnLevel
case logslog.LevelError:
return ErrorLevel
case LevelVerbose:
return TraceLevel
case LevelTrace:
return TraceLevel
case LevelNotice:
return InfoLevel
case LevelHint:
return InfoLevel
case LevelFatal:
return FatalLevel
case LevelPanic:
return PanicLevel
}
return FatalLevel
}

//

//
Expand Down
2 changes: 1 addition & 1 deletion slog/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ func TestLogCtxCtx(t *testing.T) {

l := newentry(nil)
SetDefault(l)
logctxctx(context.TODO(), WarnLevel,
logctxctx(context.TODO(), 0, WarnLevel,
"logctxctx",
)
t.Log("")
Expand Down
8 changes: 7 additions & 1 deletion slog/i.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package slog
import (
"context"
"io"
stdlog "log/slog"
"time"
)

Expand All @@ -11,6 +12,11 @@ type (
Logger interface {
EntryI
BuilderI

// Log(ctx context.Context, level Level, msg string, args ...any)

// Log to log/slog
Log(ctx context.Context, level stdlog.Level, msg string, args ...any)
}

// EntryI is a small and efficient tiny logger, which is the entity of real logger.
Expand Down Expand Up @@ -99,7 +105,7 @@ type (
EnabledContext(ctx context.Context, requestingLevel Level) bool

LogAttrs(ctx context.Context, level Level, msg string, args ...any) // Attr, Attrs in args will be recognized as is
Log(ctx context.Context, level Level, msg string, args ...any) // Attr, Attrs in args will be recognized as is
Logit(ctx context.Context, level Level, msg string, args ...any) // Attr, Attrs in args will be recognized as is

// SetSkip is very similar with WithSkip but no child logger
// created, it modifies THIS logger.
Expand Down
19 changes: 15 additions & 4 deletions slog/i_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func TestSlogBasic2(t *testing.T) {

func newMyLogger() *mylogger {
s := &mylogger{
slog.New("mylogger").WithLevel(slog.InfoLevel),
slog.New("mylogger").SetLevel(slog.InfoLevel),
true,
1, // for ur own Infof, another 1 frame need to be ignored.
}
Expand Down Expand Up @@ -120,7 +120,7 @@ func TestSlogBasic3CustomVerbsInUrOwnLogger(t *testing.T) {
}

func newMyLogger2() *mylogger2 {
l := slog.New("mylogger").WithLevel(slog.InfoLevel)
l := slog.New("mylogger").SetLevel(slog.InfoLevel)
s := &mylogger2{
l,
true,
Expand Down Expand Up @@ -197,6 +197,14 @@ func TestSlogJSON(t *testing.T) {
"method", "GET",
"time_taken_ms", // the value for this key is missing
)

logger1 := slog.New().SetJSONMode(true).SetLevel(slog.DebugLevel)

logger1.Debug("Debug message") //
logger1.Info("Info message") //
logger1.Warn("Warning message")
logger1.Error("Error message")

}

func TestSlogLogfmt(t *testing.T) {
Expand Down Expand Up @@ -249,13 +257,16 @@ func TestSlogSetDefault(t *testing.T) {
defer slog.SaveLevelAndSet(slog.WarnLevel)
defer slog.SaveFlagsAndMod(slog.LattrsR)() // add, remove, or set flags

logger := slog.New().WithJSONMode().WithLevel(slog.InfoLevel).With(m2AttrsAsAnySlice()...)
logger := slog.New().SetJSONMode().SetLevel(slog.InfoLevel).Set(m2AttrsAsAnySlice()...)

slog.SetDefault(logger)

slog.Info("Info message") // JSON mode here

logger.WithColorMode() // modify logger settings, and reacting into Default()
l := logger.WithColorMode() // make a child logger,
l.Error("Error message") // and apply to color format

logger.SetColorMode()
slog.Error("Error message") // now it's in colorful mode.
}

Expand Down
5 changes: 4 additions & 1 deletion slog/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ package slog
// slog.NewAttrs("attr2", 3, "attr3", 4.1),
// "attr4", true, "attr3", "string",
// slog.WithLevel(slog.DebugLevel), // an Opt here is allowed
// )
// ).SetLevel(slog.DebugLevel) // Both SetXXX and WithXXX can be used
//
// In using streaming calls, both SetXXX and WithXXX can be
// used. But WithXXX will make a new child logger instance.
//
// The logger name is a unique name. Reusing a used name will
// pick the exact child.
Expand Down
13 changes: 8 additions & 5 deletions slog/new_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ import (
"errors"
"fmt"
"io"
logslog "log/slog"
"os"
"strings"
"testing"
"time"
)

func TestNewLogger(t *testing.T) {
l := New(WithJSONMode(false, false),
l := New(
WithJSONMode(false, false),
WithColorMode(false),
WithUTCMode(false, true, false),
WithTimeFormat("", "", time.RFC3339Nano),
Expand Down Expand Up @@ -48,7 +50,7 @@ func TestNewChildLogger(t *testing.T) {

l.Warn("l warn msg", "local", false, "n", l.Name())

lc1 := l.New("c1").WithAttrs(NewAttr("lc1", true))
lc1 := l.New("c1").SetAttrs(NewAttr("lc1", true))
llc1 := lc1 // lc1.(*Entry)
// assert.Equal(t, llc1.owner, ll.Entry)
if llc1.owner != ll.Entry {
Expand All @@ -60,7 +62,7 @@ func TestNewChildLogger(t *testing.T) {

lc1.Warn("lc1 warn msg", "local", false)

lc2 := lc1.New("c2").WithAttrs(NewAttr("lc2", true))
lc2 := lc1.New("c2").SetAttrs(NewAttr("lc2", true))
llc2 := lc2 // lc2.(*Entry)
// assert.Equal(t, llc2.owner, lc1.Entry)
if llc2.owner != llc1 {
Expand All @@ -74,7 +76,7 @@ func TestNewChildLogger(t *testing.T) {
lc1.Warn("lc1 warn msg again", "local", false)
lc2.Warn("lc2 warn msg again", "local", false)

lc3 := lc1.New("c3").WithAttrs(NewAttr("lc3", true), NewAttr("lc1", 1))
lc3 := lc1.New("c3").SetAttrs(NewAttr("lc3", true), NewAttr("lc1", 1))
llc3 := lc3 // lc3.(*Entry)
if llc3.owner != llc1 {
t.Error("llc3.owner should equal with lc1.Entry")
Expand Down Expand Up @@ -302,7 +304,8 @@ func TestWithWriter(t *testing.T) {
l.OKContext(ctx, "ok")
l.SuccessContext(ctx, "success")
l.FailContext(ctx, "fail")
l.Log(ctx, AlwaysLevel, "log")
l.Logit(ctx, AlwaysLevel, "log")
l.Log(ctx, logslog.LevelError, "log")
}

//
Expand Down

0 comments on commit e51f96b

Please sign in to comment.