diff --git a/utils/utils.go b/utils/utils.go index 7e59264be5..558b191be9 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -54,9 +54,17 @@ func CallerFrame() runtime.Frame { // FileWithLineNum return the file name and line number of the current file func FileWithLineNum() string { - frame := CallerFrame() - if frame.PC != 0 { - return string(strconv.AppendInt(append([]byte(frame.File), ':'), int64(frame.Line), 10)) + pcs := [13]uintptr{} + // the third caller usually from gorm internal + len := runtime.Callers(3, pcs[:]) + frames := runtime.CallersFrames(pcs[:len]) + for i := 0; i < len; i++ { + // second return value is "more", not "ok" + frame, _ := frames.Next() + if (!strings.HasPrefix(frame.File, gormSourceDir) || + strings.HasSuffix(frame.File, "_test.go")) && !strings.HasSuffix(frame.File, ".gen.go") { + return string(strconv.AppendInt(append([]byte(frame.File), ':'), int64(frame.Line), 10)) + } } return "" diff --git a/utils/utils_test.go b/utils/utils_test.go index 1b8923258c..b69f9a4340 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -4,7 +4,9 @@ import ( "database/sql" "database/sql/driver" "errors" + "fmt" "math" + "runtime" "strings" "testing" "time" @@ -199,3 +201,20 @@ func TestRTrimSlice(t *testing.T) { }) } } + +// Define the where function for testing +func where() string { + return FileWithLineNum() +} + +func TestFileWithLineNum(t *testing.T) { + _, _, expectedLine, _ := runtime.Caller(0) + actual := where() // Called from next line + expectedLine++ // where() is called one line after Caller(0) + + expectedFile := "utils_test.go" + expectedStr := fmt.Sprintf("%s:%d", expectedFile, expectedLine) + if !strings.Contains(actual, expectedStr) { + t.Errorf("Expected %s, but got %s", expectedStr, actual) + } +}