From cc79692d68801f1c862b43a18d4ce5989da695d2 Mon Sep 17 00:00:00 2001 From: johnson Date: Tue, 26 May 2020 14:33:56 +0800 Subject: [PATCH] make caller filepath package/file style this code is from zap https://github.com/uber-go/zap/blob/9a9fa7d4b5f07a9b634983678a65b5525f81e58b/zapcore/entry.go#L101 --- logger/default.go | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/logger/default.go b/logger/default.go index 828b4867..70aeb476 100644 --- a/logger/default.go +++ b/logger/default.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "os" - "path/filepath" "runtime" "sort" "strings" @@ -55,9 +54,28 @@ func copyFields(src map[string]interface{}) map[string]interface{} { 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 { - parts := strings.Split(loggingFilePath, string(filepath.Separator)) - return parts[len(parts)-1] + // To make sure we trim the path correctly on Windows too, we + // 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{}) {