Skip to content

Commit

Permalink
✅ test: add more unit test cases for logger, record
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 15, 2023
1 parent c00791b commit 8468ea4
Show file tree
Hide file tree
Showing 8 changed files with 179 additions and 150 deletions.
17 changes: 17 additions & 0 deletions common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,20 @@ func (h testHandler) Handle(_ *slog.Record) error {
}
return nil
}

type testFormatter struct {
errOnFormat bool
}

func newTestFormatter(errOnFormat ...bool) *testFormatter {
return &testFormatter{
errOnFormat: len(errOnFormat) > 0 && errOnFormat[0],
}
}

func (f testFormatter) Format(r *slog.Record) ([]byte, error) {
if f.errOnFormat {
return nil, errorx.Raw("format error")
}
return []byte(r.Message), nil
}
37 changes: 10 additions & 27 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,16 @@ import (
"context"
"sync"
"time"

"github.com/gookit/gsr"
)

// SLogger interface
type SLogger interface {
gsr.Logger
Log(level Level, v ...any)
Logf(level Level, format string, v ...any)
}

// LoggerFn func
type LoggerFn func(l *Logger)

// Logger log dispatcher definition.
//
// The logger implements the `github.com/gookit/gsr.Logger`
type Logger struct {
name string
// lock for write logs
mu sync.Mutex
// log latest error
// logger latest error
err error

// log handlers for logger
Expand All @@ -34,6 +22,8 @@ type Logger struct {

// reusable empty record
recordPool sync.Pool
// handlers on exit.
exitHandlers []func()

//
// logger options
Expand All @@ -45,12 +35,11 @@ type Logger struct {
ReportCaller bool
CallerSkip int
CallerFlag uint8
// BackupArgs backup log input args to Record.Args
BackupArgs bool
// TimeClock custom time clock, timezone
TimeClock ClockFn

// handlers on exit.
exitHandlers []func()
// custom exit, panic handle.
// custom exit, panic handler.
ExitFunc func(code int)
PanicFunc func(v any)
}
Expand Down Expand Up @@ -150,7 +139,6 @@ func (l *Logger) FlushTimeout(timeout time.Duration) {
if err := l.lockAndFlushAll(); err != nil {
printlnStderr("slog.FlushTimeout: flush logs error: ", err)
}

done <- true
}()

Expand All @@ -161,9 +149,7 @@ func (l *Logger) FlushTimeout(timeout time.Duration) {
}
}

// Sync flushes buffered logs (if any).
//
// alias of the Flush()
// Sync flushes buffered logs (if any). alias of the Flush()
func (l *Logger) Sync() error { return Flush() }

// Flush flushes all the logs and attempts to "sync" their data to disk.
Expand Down Expand Up @@ -299,18 +285,15 @@ func (l *Logger) PushHandlers(hs ...Handler) {
}

// SetHandlers for the logger
func (l *Logger) SetHandlers(hs []Handler) {
l.handlers = hs
}
func (l *Logger) SetHandlers(hs []Handler) { l.handlers = hs }

// AddProcessor to the logger
func (l *Logger) AddProcessor(p Processor) { l.processors = append(l.processors, p) }

// PushProcessor to the logger
// alias of AddProcessor()
// PushProcessor to the logger, alias of AddProcessor()
func (l *Logger) PushProcessor(p Processor) { l.processors = append(l.processors, p) }

// AddProcessors to the logger
// AddProcessors to the logger. alias of AddProcessor()
func (l *Logger) AddProcessors(ps ...Processor) { l.processors = append(l.processors, ps...) }

// SetProcessors for the logger
Expand Down
39 changes: 28 additions & 11 deletions record.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,10 @@ type Record struct {
// Buffer Can use Buffer on formatter
// Buffer *bytes.Buffer

// cache the r.Time.Nanosecond() / 1000
// microSecond int
// stacks []byte
// formatted []byte
// field caches mapping for optimize performance. TODO use map[string][]byte ?
// strMp map[string]string
// log input args backups, from log() and logf().
// default its dont use in formatter.
Fmt string
Args []any
}

func newRecord(logger *Logger) *Record {
Expand Down Expand Up @@ -97,10 +95,6 @@ func (r *Record) WithError(err error) *Record {
// WithData on record
func (r *Record) WithData(data M) *Record {
nr := r.Copy()
// if nr.Data == nil {
// nr.Data = data
// }

nr.Data = data
return nr
}
Expand Down Expand Up @@ -193,13 +187,20 @@ func (r *Record) AddData(data M) *Record {
func (r *Record) AddValue(key string, value any) *Record {
if r.Data == nil {
r.Data = make(M, 8)
return r
}

r.Data[key] = value
return r
}

// Value get Data value from record
func (r *Record) Value(key string) any {
if r.Data == nil {
return nil
}
return r.Data[key]
}

// SetExtra information on record
func (r *Record) SetExtra(data M) *Record {
r.Extra = data
Expand Down Expand Up @@ -262,6 +263,14 @@ func (r *Record) SetFields(fields M) *Record {
return r
}

// Field value get from record
func (r *Record) Field(key string) any {
if r.Fields == nil {
return nil
}
return r.Fields[key]
}

//
// ---------------------------------------------------------------------------
// Add log message with builder
Expand Down Expand Up @@ -297,6 +306,9 @@ func (r *Record) SetFields(fields M) *Record {

func (r *Record) log(level Level, args []any) {
r.Level = level
if r.logger.BackupArgs {
r.Args = args
}

// r.Message = strutil.Byte2str(formatArgsWithSpaces(args)) // will reduce memory allocation once
r.Message = formatArgsWithSpaces(args)
Expand All @@ -305,6 +317,11 @@ func (r *Record) log(level Level, args []any) {
}

func (r *Record) logf(level Level, format string, args []any) {
if r.logger.BackupArgs {
r.Fmt = format
r.Args = args
}

r.Level = level
r.Message = fmt.Sprintf(format, args...)
// r.logWrite(level)
Expand Down
15 changes: 15 additions & 0 deletions record_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,19 @@ func TestRecord_AddData(t *testing.T) {
fmt.Print(s)
assert.Contains(t, s, "log message add data2")
assert.Contains(t, s, "key01:val01")
assert.Eq(t, "val01", r.Value("key01"))

// - add value
r.AddValue("key01", "val02").Println("log message add value")
s = w.StringReset()
fmt.Print(s)
assert.Contains(t, s, "log message add value")
assert.Contains(t, s, "key01:val02")
// - first add value
nr := &slog.Record{}
assert.Nil(t, nr.Value("key01"))
nr.AddValue("key01", "val02")
assert.Eq(t, "val02", nr.Value("key01"))

// -with data
r.CallerFlag = slog.CallerFlagFcName
Expand Down Expand Up @@ -151,6 +157,15 @@ func TestRecord_AddFields(t *testing.T) {

r.AddFields(slog.M{"app": "goods"})
assert.NotEmpty(t, r.Fields)

r = r.WithFields(slog.M{"f2": "v2"})
assert.Eq(t, "v2", r.Field("f2"))

// - first add field
nr := slog.Record{}
assert.Nil(t, nr.Field("f3"))
nr.AddField("f3", "val02")
assert.Eq(t, "val02", nr.Field("f3"))
}

func TestRecord_SetFields(t *testing.T) {
Expand Down
Loading

0 comments on commit 8468ea4

Please sign in to comment.