make caller filepath package/file style

this code is from zap
9a9fa7d4b5/zapcore/entry.go (L101)
This commit is contained in:
johnson 2020-05-26 14:33:56 +08:00
parent 796a598b37
commit cc79692d68

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"os" "os"
"path/filepath"
"runtime" "runtime"
"sort" "sort"
"strings" "strings"
@ -55,9 +54,28 @@ func copyFields(src map[string]interface{}) map[string]interface{} {
return dst return dst
} }
// logCallerfilePath returns a package/file:line description of the caller,
// preserving only the leaf directory name and file name.
func logCallerfilePath(loggingFilePath string) string { func logCallerfilePath(loggingFilePath string) string {
parts := strings.Split(loggingFilePath, string(filepath.Separator)) // To make sure we trim the path correctly on Windows too, we
return parts[len(parts)-1] // counter-intuitively need to use '/' and *not* os.PathSeparator here,
// because the path given originates from Go stdlib, specifically
// runtime.Caller() which (as of Mar/17) returns forward slashes even on
// Windows.
//
// See https://github.com/golang/go/issues/3335
// and https://github.com/golang/go/issues/18151
//
// for discussion on the issue on Go side.
idx := strings.LastIndexByte(loggingFilePath, '/')
if idx == -1 {
return loggingFilePath
}
idx = strings.LastIndexByte(loggingFilePath[:idx], '/')
if idx == -1 {
return loggingFilePath
}
return loggingFilePath[idx+1:]
} }
func (l *defaultLogger) Log(level Level, v ...interface{}) { func (l *defaultLogger) Log(level Level, v ...interface{}) {