github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/pkg/caller/caller.go (about)

     1  package caller
     2  
     3  import (
     4  	"runtime"
     5  	"strings"
     6  )
     7  
     8  const (
     9  	packageNameToTrim  = "github.com/ShoshinNikita/budget-manager/"
    10  	internalPathToTrim = "internal/"
    11  )
    12  
    13  // GetFormattedCaller returns formatted caller.
    14  // It uses 'FormatCaller' function to format '*runtime.Func'
    15  func GetFormattedCaller(skip int) string {
    16  	pc, _, _, ok := runtime.Caller(skip)
    17  	if !ok {
    18  		return ""
    19  	}
    20  
    21  	details := runtime.FuncForPC(pc)
    22  	if details == nil {
    23  		return ""
    24  	}
    25  
    26  	return FormatCaller(details)
    27  }
    28  
    29  // FormatCaller returns formatted '*runtime.Func': something like 'some/package/path.Struct.Func'
    30  func FormatCaller(details *runtime.Func) string {
    31  	// funcName looks like "github.com/username/project/internal/web.Service.Func"
    32  	funcName := details.Name()
    33  
    34  	// Trim "github.com/username/project/"
    35  	funcName = strings.TrimPrefix(funcName, packageNameToTrim)
    36  	// Trim "internal/"
    37  	funcName = strings.TrimPrefix(funcName, internalPathToTrim)
    38  
    39  	return funcName
    40  }