Skip to content

Commit

Permalink
up: support report caller info
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jul 19, 2020
1 parent 43e3cb2 commit 76c02ca
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 9 deletions.
1 change: 1 addition & 0 deletions _example/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ github.com/gookit/slog v0.0.0-20200718054058-a7053e5b311b h1:VjstQGjCdqf79e2p6Bd
github.com/gookit/slog v0.0.0-20200718054058-a7053e5b311b/go.mod h1:ObcDZB9gjOVltZnvB4frHW2Mf5pFWnoJ9601VIDMEIE=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
Expand Down
7 changes: 5 additions & 2 deletions define.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,20 @@ const flushInterval = 30 * time.Second

const (
FieldKeyTime = "time"
// FieldKeyDate = "date"
FieldKeyData = "data"
FieldKeyFunc = "func"
FieldKeyFile = "file"
// FieldKeyDate = "date"

FieldKeyDatetime = "datetime"
FieldKeyDatetime = "datetime"
FieldKeyPosition = "position"
FieldKeyTimestamp = "timestamp"

FieldKeyLevel = "level"
FieldKeyError = "error"
FieldKeyExtra = "extra"

FieldKeyCaller = "caller"
FieldKeyChannel = "channel"
FieldKeyMessage = "message"
)
Expand Down
2 changes: 2 additions & 0 deletions formatter_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ func (f *JSONFormatter) Format(r *Record) ([]byte,error) {
}

logData[outName] = r.Time.Format(f.TimeFormat)
case field == FieldKeyCaller && r.Caller != nil:
logData[outName] = formatCallerToString(r.Caller)
case field == FieldKeyLevel:
logData[outName] = r.LevelName
case field == FieldKeyChannel:
Expand Down
6 changes: 5 additions & 1 deletion formatter_text.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/gookit/goutil/strutil"
)

const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] {{message}} {{data}} {{extra}}\n"
const DefaultTemplate = "[{{datetime}}] [{{channel}}] [{{level}}] [{{caller}}] {{message}} {{data}} {{extra}}\n"

// ColorTheme for format log to console
var ColorTheme = map[Level]color.Color{
Expand Down Expand Up @@ -90,6 +90,8 @@ func (f *TextFormatter) formatNoColor(r *Record) ([]byte, error) {
}

tplData[tplVar] = r.Time.Format(f.TimeFormat)
case field == FieldKeyCaller && r.Caller != nil: // caller eg: "logger_test.go:48"
tplData[tplVar] = formatCallerToString(r.Caller)
case field == FieldKeyLevel:
tplData[tplVar] = r.LevelName
case field == FieldKeyChannel:
Expand Down Expand Up @@ -130,6 +132,8 @@ func (f *TextFormatter) formatWithColor(r *Record) ([]byte, error) {
}

tplData[tplVar] = r.Time.Format(f.TimeFormat)
case field == FieldKeyCaller && r.Caller != nil: // caller eg: "logger_test.go:48"
tplData[tplVar] = formatCallerToString(r.Caller)
case field == FieldKeyLevel:
tplData[tplVar] = f.renderColorByLevel(r.LevelName, r.Level)
case field == FieldKeyChannel:
Expand Down
2 changes: 1 addition & 1 deletion handler/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type ConsoleHandler struct {
// NewConsoleHandler create new ConsoleHandler
func NewConsoleHandler(levels []slog.Level) *ConsoleHandler {
h := &ConsoleHandler{}
h.Out = os.Stdout
h.Output = os.Stdout
h.Levels = levels

// create new formatter
Expand Down
8 changes: 4 additions & 4 deletions handler/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ import (
type StreamHandler struct {
BaseHandler

// Out io.WriteCloser
Out io.Writer
// Output io.WriteCloser
Output io.Writer

UseLock bool
}

// NewStreamHandler create new StreamHandler
func NewStreamHandler(out io.Writer, levels []slog.Level) *StreamHandler {
return &StreamHandler{
Out: out,
Output: out,
BaseHandler: BaseHandler{
Levels: levels,
},
Expand All @@ -39,7 +39,7 @@ func (h *StreamHandler) Handle(record *slog.Record) error {
return err
}

_, err = h.Out.Write(bts)
_, err = h.Output.Write(bts)
return err
}

Expand Down
5 changes: 5 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ func New() *Logger {
return NewWithName("")
}

// NewWithConfig create an new logger with config func
func NewWithConfig(fn func(logger *Logger)) *Logger {
return New().Configure(fn)
}

// NewWithHandlers create an new logger with handlers
func NewWithHandlers(hs ...Handler) *Logger {
logger := NewWithName("")
Expand Down
28 changes: 28 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package slog_test

import (
"bytes"
"testing"

"github.com/gookit/slog"
"github.com/gookit/slog/handler"
"github.com/stretchr/testify/assert"
)

Expand All @@ -21,3 +23,29 @@ func TestLoggerBasic(t *testing.T) {
func TestLogger_AddHandlers(t *testing.T) {

}

type bufferHandler struct {
handler.BaseHandler
}

func (h *bufferHandler) Handle(*slog.Record) error {
panic("implement me")
}

func TestLogger_ReportCaller(t *testing.T) {
l := slog.NewWithConfig(func(logger *slog.Logger) {
logger.ReportCaller = true
})

var buf bytes.Buffer
h := handler.NewStreamHandler(&buf, slog.AllLevels)
h.SetFormatter(slog.NewJSONFormatter(func(f *slog.JSONFormatter) {
f.Fields = append(f.Fields, slog.FieldKeyCaller)
}))

l.AddHandler(h)
l.Info("message")

str := buf.String()
assert.Contains(t, str, `"caller":"logger_test.go`)
}
2 changes: 1 addition & 1 deletion slog.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func (sl *SugaredLogger) Reset() {
// It is directly available without any additional configuration
var std = newStdLogger()

func newStdLogger() *SugaredLogger {
func newStdLogger() *SugaredLogger {
return NewSugaredLogger(os.Stdout, ErrorLevel).Configure(func(sl *SugaredLogger) {
sl.SetName("stdLogger")
// auto enable console color
Expand Down
9 changes: 9 additions & 0 deletions testdata/runtime.Frame.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
*runtime.Frame {
PC: 0x73139f,
Func: &runtime.Func{opaque:struct {}{}},
Function: "github.com/gookit/slog_test.TestLogger_ReportCaller",
File: "F:/work/go/gookit/slog/logger_test.go",
Line: 47,
Entry: 0x7311b0,
funcInfo: "<runtime.funcInfo Value>",
}
9 changes: 9 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package slog

import (
"bytes"
"fmt"
"path"
"runtime"
"strings"
"sync"
Expand Down Expand Up @@ -87,6 +89,13 @@ func getCaller(maxCallerDepth int) *runtime.Frame {
return nil
}

func formatCallerToString(rf *runtime.Frame) string {
// TODO format different string

// eg: "logger_test.go:48"
return fmt.Sprintf("%s:%d", path.Base(rf.File), rf.Line)
}

// from glog
// func timeoutFlush(timeout time.Duration) {
// done := make(chan bool, 1)
Expand Down

0 comments on commit 76c02ca

Please sign in to comment.