如何在运行时的给定调用中找到包名称?

For logging purpose I want to write a function which will print a package name. I can do it for a directory name:

// file is the full file name
// 4 - how many calls we want to go up in a stack trace.
_, file, line, ok := runtime.Caller(4) 

... but can't find a way for package name (package name can be different from directory name).

I came across a similar problem - from a package path how do you get the package name. The best solution I found is to exec the "go list" command. Not ideal but I came up blank elsewhere.

In my case I also had a problem that sometimes the package is an empty directory. With no source files, "go list" throws an error, so I added a function to create a sensible package name from the path.

Here's the code:

func getPackageName(path string) string {
    output, err := exec.Command("go", "list", "-f", "{{.Name}}", path).CombinedOutput()
    if err != nil {
        return guessPackageName(path)
    }
    return strings.TrimSpace(string(output))
}

func guessPackageName(path string) string {
    preferred := path
    if strings.HasSuffix(preferred, "/") {
        // training slashes are usually tolerated, so we can get rid of one if it exists
        preferred = preferred[:len(preferred)-1]
    }
    if strings.Contains(preferred, "/") {
        // if the path contains a "/", use the last part
        preferred = preferred[strings.LastIndex(preferred, "/")+1:]
    }
    if strings.Contains(preferred, "-") {
        // the name usually follows a hyphen - e.g. github.com/foo/go-bar
        // if the package name contains a "-", use the last part
        preferred = preferred[strings.LastIndex(preferred, "-")+1:]
    }
    if strings.Contains(preferred, ".") {
        // dot is commonly usually used as a version - e.g. github.com/foo/bar.v1
        // if the package name contains a ".", use the first part
        preferred = preferred[:strings.LastIndex(preferred, ".")]
    }
    return preferred
}