Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update slog code to work with Go 1.21 #74

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/charmbracelet/log

go 1.17
go 1.21

require (
github.com/charmbracelet/lipgloss v0.7.1
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
Expand All @@ -31,7 +30,6 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Expand Down
2 changes: 1 addition & 1 deletion json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,5 +177,5 @@ func TestJsonCustomKey(t *testing.T) {
logger.SetFormatter(JSONFormatter)
logger.SetReportTimestamp(true)
logger.Info("info")
require.Equal(t, "{\"lvl\":\"info\",\"msg\":\"info\",\"time\":\"0001/01/01 00:00:00\"}\n", buf.String())
require.Equal(t, "{\"lvl\":\"info\",\"msg\":\"info\",\"time\":\"0002/01/01 00:00:00\"}\n", buf.String())
}
24 changes: 23 additions & 1 deletion level.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package log

import "strings"
import (
"strings"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we remove this line, then goimports will shuffle this around better

"log/slog"
)

// Level is a logging level.
type Level int32
Expand Down Expand Up @@ -55,3 +59,21 @@ func ParseLevel(level string) Level {
return InfoLevel
}
}

// fromSlogLevel converts slog.Level to log.Level.
var fromSlogLevel = map[slog.Level]Level{
slog.LevelDebug: DebugLevel,
slog.LevelInfo: InfoLevel,
slog.LevelWarn: WarnLevel,
slog.LevelError: ErrorLevel,
slog.Level(12): FatalLevel,
}

// toSlogLevel converts log.Level to slog.Level.
var toSlogLevel = map[Level]slog.Level{
DebugLevel: slog.LevelDebug,
InfoLevel: slog.LevelInfo,
WarnLevel: slog.LevelWarn,
ErrorLevel: slog.LevelError,
FatalLevel: slog.Level(12),
}
119 changes: 94 additions & 25 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
Expand All @@ -10,6 +11,9 @@
"strings"
"sync"
"sync/atomic"
"time"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as above, we should drop the newline here, so goimports merges it in better

"log/slog"

"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
Expand Down Expand Up @@ -48,6 +52,53 @@
helpers *sync.Map
}

// Enabled reports whether the logger is enabled for the given level.
//
// Implements slog.Handler.
func (l *Logger) Enabled(_ context.Context, level slog.Level) bool {
return atomic.LoadInt32(&l.level) <= int32(fromSlogLevel[level])
}

// Handle handles the Record. It will only be called if Enabled returns true.
//
// Implements slog.Handler.
func (l *Logger) Handle(_ context.Context, record slog.Record) error {
fields := make([]interface{}, 0, record.NumAttrs()*2)
record.Attrs(func(a slog.Attr) bool {

Check warning on line 67 in logger.go

View check run for this annotation

Codecov / codecov/patch

logger.go#L67

Added line #L67 was not covered by tests
fields = append(fields, a.Key, a.Value.String())
return true

Check warning on line 69 in logger.go

View check run for this annotation

Codecov / codecov/patch

logger.go#L69

Added line #L69 was not covered by tests
})
// Get the caller frame using the record's PC.
frames := runtime.CallersFrames([]uintptr{record.PC})
frame, _ := frames.Next()
l.handle(fromSlogLevel[record.Level], record.Time, []runtime.Frame{frame}, record.Message, fields...)
return nil
}

// WithAttrs returns a new Handler with the given attributes added.
//
// Implements slog.Handler.
func (l *Logger) WithAttrs(attrs []slog.Attr) slog.Handler {
fields := make([]interface{}, 0, len(attrs)*2)
for _, attr := range attrs {
fields = append(fields, attr.Key, attr.Value)
}
return l.With(fields...)
}

// WithGroup returns a new Handler with the given group name prepended to the
// current group name or prefix.
//
// Implements slog.Handler.
func (l *Logger) WithGroup(name string) slog.Handler {
if l.prefix != "" {
name = l.prefix + "." + name
}
return l.WithPrefix(name)
}

var _ slog.Handler = (*Logger)(nil)

func (l *Logger) log(level Level, msg interface{}, keyvals ...interface{}) {
if atomic.LoadUint32(&l.isDiscard) != 0 {
return
Expand All @@ -58,24 +109,44 @@
return
}

var frame runtime.Frame
if l.reportCaller {
// Skip log.log, the caller, and any offset added.
frames := l.frames(l.callerOffset + 2)
for {
f, more := frames.Next()
_, helper := l.helpers.Load(f.Function)
if !helper || !more {
// Found a frame that wasn't a helper function.
// Or we ran out of frames to check.
frame = f
break
}
}
}
l.handle(level, l.timeFunc(), []runtime.Frame{frame}, msg, keyvals...)
}

func (l *Logger) handle(level Level, ts time.Time, frames []runtime.Frame, msg interface{}, keyvals ...interface{}) {
l.mu.Lock()
defer l.mu.Unlock()
defer l.b.Reset()

var kvs []interface{}
if l.reportTimestamp {
kvs = append(kvs, TimestampKey, l.timeFunc())
if l.reportTimestamp && !ts.IsZero() {
kvs = append(kvs, TimestampKey, ts)
}

if level != noLevel {
kvs = append(kvs, LevelKey, level)
}

if l.reportCaller {
// Call stack is log.Error -> log.log (2)
file, line, fn := l.fillLoc(l.callerOffset + 2)
caller := l.callerFormatter(file, line, fn)
kvs = append(kvs, CallerKey, caller)
if l.reportCaller && len(frames) > 0 && frames[0].PC != 0 {
file, line, fn := l.location(frames)
if file != "" {
caller := l.callerFormatter(file, line, fn)
kvs = append(kvs, CallerKey, caller)
}
}

if l.prefix != "" {
Expand Down Expand Up @@ -118,34 +189,32 @@
}

func (l *Logger) helper(skip int) {
_, _, fn := location(skip + 1)
l.helpers.LoadOrStore(fn, struct{}{})
var pcs [1]uintptr
// Skip runtime.Callers, and l.helper
n := runtime.Callers(skip+2, pcs[:])
frames := runtime.CallersFrames(pcs[:n])
frame, _ := frames.Next()
l.helpers.LoadOrStore(frame.Function, struct{}{})
}

func (l *Logger) fillLoc(skip int) (file string, line int, fn string) {
// frames returns the runtime.Frames for the caller.
func (l *Logger) frames(skip int) *runtime.Frames {
// Copied from testing.T
const maxStackLen = 50
var pc [maxStackLen]uintptr

// Skip two extra frames to account for this function
// and runtime.Callers itself.
// Skip runtime.Callers, and l.frame
n := runtime.Callers(skip+2, pc[:])
frames := runtime.CallersFrames(pc[:n])
for {
frame, more := frames.Next()
_, helper := l.helpers.Load(frame.Function)
if !helper || !more {
// Found a frame that wasn't a helper function.
// Or we ran out of frames to check.
return frame.File, frame.Line, frame.Function
}
}
return frames
}

func location(skip int) (file string, line int, fn string) {
pc, file, line, _ := runtime.Caller(skip + 1)
f := runtime.FuncForPC(pc)
return file, line, f.Name()
func (l *Logger) location(frames []runtime.Frame) (file string, line int, fn string) {
if len(frames) == 0 {
return "", 0, ""
}
f := frames[0]
return f.File, f.Line, f.Function
}

// Cleanup a path by returning the last n segments of the path only.
Expand Down
10 changes: 6 additions & 4 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ func TestOptions(t *testing.T) {
func TestCallerFormatter(t *testing.T) {
var buf bytes.Buffer
l := NewWithOptions(&buf, Options{ReportCaller: true})
file, line, fn := l.fillLoc(0)
frames := l.frames(0)
frame, _ := frames.Next()
file, line, fn := frame.File, frame.Line, frame.Function
hi := func() { l.Info("hi") }
cases := []struct {
name string
Expand All @@ -37,12 +39,12 @@ func TestCallerFormatter(t *testing.T) {
}{
{
name: "short caller formatter",
expected: fmt.Sprintf("INFO <log/options_test.go:%d> hi\n", line+1),
expected: fmt.Sprintf("INFO <log/options_test.go:%d> hi\n", line+3),
format: ShortCallerFormatter,
},
{
name: "long caller formatter",
expected: fmt.Sprintf("INFO <%s:%d> hi\n", file, line+1),
expected: fmt.Sprintf("INFO <%s:%d> hi\n", file, line+3),
format: LongCallerFormatter,
},
{
Expand All @@ -54,7 +56,7 @@ func TestCallerFormatter(t *testing.T) {
},
{
name: "custom caller formatter",
expected: fmt.Sprintf("INFO <%s:%d:%s.func1> hi\n", file, line+1, fn),
expected: fmt.Sprintf("INFO <%s:%d:%s.func1> hi\n", file, line+3, fn),
format: func(file string, line int, fn string) string {
return fmt.Sprintf("%s:%d:%s", file, line, fn)
},
Expand Down
1 change: 0 additions & 1 deletion pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ func WithPrefix(prefix string) *Logger {
// and skips it for source location information.
// It's the equivalent of testing.TB.Helper().
func Helper() {
// skip this function frame
defaultLogger.helper(1)
}

Expand Down
14 changes: 7 additions & 7 deletions pkg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func TestGlobal(t *testing.T) {
}{
{
name: "default logger info with timestamp",
expected: "0001/01/01 00:00:00 INFO info\n",
expected: "0002/01/01 00:00:00 INFO info\n",
msg: "info",
kvs: nil,
f: Info,
Expand All @@ -40,7 +40,7 @@ func TestGlobal(t *testing.T) {
},
{
name: "default logger error with timestamp",
expected: "0001/01/01 00:00:00 ERRO info\n",
expected: "0002/01/01 00:00:00 ERRO info\n",
msg: "info",
kvs: nil,
f: Error,
Expand All @@ -65,7 +65,7 @@ func TestPrint(t *testing.T) {
SetTimeFormat(DefaultTimeFormat)
Error("error")
Print("print")
assert.Equal(t, "0001/01/01 00:00:00 print\n", buf.String())
assert.Equal(t, "0002/01/01 00:00:00 print\n", buf.String())
}

func TestPrintf(t *testing.T) {
Expand All @@ -78,7 +78,7 @@ func TestPrintf(t *testing.T) {
SetTimeFormat(DefaultTimeFormat)
Errorf("error")
Printf("print")
assert.Equal(t, "0001/01/01 00:00:00 print\n", buf.String())
assert.Equal(t, "0002/01/01 00:00:00 print\n", buf.String())
}

func TestFatal(t *testing.T) {
Expand Down Expand Up @@ -125,7 +125,7 @@ func TestDebugf(t *testing.T) {
SetTimeFormat(DefaultTimeFormat)
_, file, line, _ := runtime.Caller(0)
Debugf("debug %s", "foo")
assert.Equal(t, fmt.Sprintf("0001/01/01 00:00:00 DEBU <log/%s:%d> debug foo\n", filepath.Base(file), line+1), buf.String())
assert.Equal(t, fmt.Sprintf("0002/01/01 00:00:00 DEBU <log/%s:%d> debug foo\n", filepath.Base(file), line+1), buf.String())
}

func TestInfof(t *testing.T) {
Expand All @@ -148,7 +148,7 @@ func TestWarnf(t *testing.T) {
SetTimeFunction(_zeroTime)
SetTimeFormat(DefaultTimeFormat)
Warnf("warn %s", "foo")
assert.Equal(t, "0001/01/01 00:00:00 WARN warn foo\n", buf.String())
assert.Equal(t, "0002/01/01 00:00:00 WARN warn foo\n", buf.String())
}

func TestErrorf(t *testing.T) {
Expand All @@ -172,7 +172,7 @@ func TestWith(t *testing.T) {
SetTimeFunction(_zeroTime)
SetTimeFormat(DefaultTimeFormat)
With("foo", "bar").Info("info")
assert.Equal(t, "0001/01/01 00:00:00 INFO info foo=bar\n", buf.String())
assert.Equal(t, "0002/01/01 00:00:00 INFO info foo=bar\n", buf.String())
}

func TestGetLevel(t *testing.T) {
Expand Down
39 changes: 27 additions & 12 deletions text.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,24 +124,39 @@ func escapeStringForOutput(str string, escapeQuotes bool) string {
return bb.String()
}

// isNormal indicates if the rune is one allowed to exist as an unquoted
// string value. This is a subset of ASCII, `-` through `~`.
func isNormal(r rune) bool {
return '-' <= r && r <= '~'
}

// needsQuoting returns false if all the runes in string are normal, according
// to isNormal.
func needsQuoting(str string) bool {
for _, r := range str {
if !isNormal(r) {
func needsQuoting(s string) bool {
for i := 0; i < len(s); {
b := s[i]
if b < utf8.RuneSelf {
if needsQuotingSet[b] {
return true
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError || unicode.IsSpace(r) || !unicode.IsPrint(r) {
return true
}
i += size
}

return false
}

var needsQuotingSet = [utf8.RuneSelf]bool{
'"': true,
'=': true,
}

func init() {
for i := 0; i < utf8.RuneSelf; i++ {
r := rune(i)
if unicode.IsSpace(r) || !unicode.IsPrint(r) {
needsQuotingSet[i] = true
}
}
}

func (l *Logger) textFormatter(keyvals ...interface{}) {
for i := 0; i < len(keyvals); i += 2 {
switch keyvals[i] {
Expand Down
Loading