diff --git a/pkg/logging/logger.go b/pkg/logging/logger.go index 66eed078ffb..57058f7c9cd 100644 --- a/pkg/logging/logger.go +++ b/pkg/logging/logger.go @@ -5,7 +5,7 @@ import ( "fmt" "io" "os" - "reflect" + "regexp" "runtime" "slices" "strings" @@ -76,9 +76,10 @@ type Fields map[string]interface{} // logCallerTrimmer is used to trim the caller paths to be relative to the project root func logCallerTrimmer(frame *runtime.Frame) (function string, file string) { - indexOfModule := strings.Index(strings.ToLower(frame.File), ProjectDirectoryName) - if indexOfModule != -1 { - file = frame.File[indexOfModule+len(ProjectDirectoryName):] + r := regexp.MustCompile(fmt.Sprintf(`.*/([^/]*%s[^/]*)/.*`, ProjectDirectoryName)) + matches := r.FindStringSubmatch(strings.ToLower(frame.File)) + if len(matches) > 1 { + file = matches[1] } else { file = frame.File } diff --git a/pkg/logging/logger_test.go b/pkg/logging/logger_test.go index 7751b24c8eb..471534d52a9 100644 --- a/pkg/logging/logger_test.go +++ b/pkg/logging/logger_test.go @@ -6,10 +6,63 @@ import ( "io" "os" "path/filepath" + "runtime" "testing" "time" ) +func TestLogCallerTrimmer(t *testing.T) { + t.Run("dir name is just lakeFS", func(t *testing.T) { + frame := &runtime.Frame{ + File: "lakefs/to/main.go", + Line: 42, + Function: "main.someFunction", + } + wantFile := "lakefs/to/main.go:42" + wantFunction := "main.someFunction" + resultFunction, resultFile := logCallerTrimmer(frame) + if resultFile != wantFile { + t.Fatalf("Result File '%s', should be '%s'", resultFile, wantFile) + } + if resultFunction != wantFunction { + t.Fatalf("Result Function '%s', should be '%s'", resultFunction, wantFunction) + } + }) + + t.Run("dir name is lakeFS-foo", func(t *testing.T) { + frame := &runtime.Frame{ + File: "lakefs-foo/to/main.go", + Line: 42, + Function: "main.someFunction", + } + wantFile := "lakefs-foo/to/main.go:42" + wantFunction := "main.someFunction" + resultFunction, resultFile := logCallerTrimmer(frame) + if resultFile != wantFile { + t.Fatalf("Result File '%s', should be '%s'", resultFile, wantFile) + } + if resultFunction != wantFunction { + t.Fatalf("Result Function '%s', should be '%s'", resultFunction, wantFunction) + } + }) + t.Run("dir name is just full absolute path", func(t *testing.T) { + frame := &runtime.Frame{ + File: "Users/Apps/lakeFS-foo/to/main.go", + Line: 42, + Function: "main.someFunction", + } + wantFile := "lakeFS-foo/to/main.go:42" + wantFunction := "main.someFunction" + resultFunction, resultFile := logCallerTrimmer(frame) + if resultFile != wantFile { + t.Fatalf("Result File '%s', should be '%s'", resultFile, wantFile) + } + if resultFunction != wantFunction { + t.Fatalf("Result Function '%s', should be '%s'", resultFunction, wantFunction) + } + }) +} + func TestSetOutputs(t *testing.T) { t.Run("default", func(t *testing.T) { currentOut := defaultLogger.Out