Skip to content

Commit

Permalink
Add Logger values into Msg before handling and log values
Browse files Browse the repository at this point in the history
  • Loading branch information
anacrolix committed Jun 27, 2024
1 parent 0e1afd7 commit cd912c6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
15 changes: 11 additions & 4 deletions logger-core.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package log
import (
"fmt"
"path/filepath"
"slices"
)

// loggerCore is the essential part of Logger.
Expand All @@ -24,7 +25,8 @@ func (l loggerCore) asLogger() Logger {

// Returns a logger that adds the given values to logged messages.
func (l loggerCore) WithValues(v ...interface{}) Logger {
l.values = append(l.values, v...)
l.assertNonZero()
l.values = append(slices.Clone(l.values), v...)
return l.asLogger()
}

Expand Down Expand Up @@ -91,6 +93,7 @@ func (l loggerCore) lazyLog(level Level, skip int, f func() Msg) {
for i := len(l.msgMaps) - 1; i >= 0; i-- {
r = l.msgMaps[i](r)
}
r = r.WithValues(l.values...)
l.handle(level, r, names)
}

Expand All @@ -102,9 +105,7 @@ func (l loggerCore) handle(level Level, m Msg, names []string) {
Level: level,
Names: names,
}
if !l.nonZero {
panic(fmt.Sprintf("Logger uninitialized. names=%q", l.names))
}
l.assertNonZero()
for _, h := range l.Handlers {
h.Handle(r)
}
Expand All @@ -123,3 +124,9 @@ func (l *loggerCore) SetHandlers(h ...Handler) {
l.Handlers = h
l.nonZero = true
}

func (l *loggerCore) assertNonZero() {
if !l.nonZero {
panic(fmt.Sprintf("Logger uninitialized. names=%q", l.names))
}
}
10 changes: 10 additions & 0 deletions stream-handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package log

import (
"fmt"
"io"
)

Expand Down Expand Up @@ -34,6 +35,15 @@ func twoLineFormatter(msg Record) []byte {
}
b = append(b, "]\n "...)
b = append(b, msg.Text()...)
msg.Values(func(value interface{}) (more bool) {
b = append(b, ' ')
if item, ok := value.(item); ok {
b = fmt.Appendf(b, "%s=%s", item.key, item.value)
} else {
b = fmt.Append(b, value)
}
return true
})
if b[len(b)-1] != '\n' {
b = append(b, '\n')
}
Expand Down

0 comments on commit cd912c6

Please sign in to comment.