douwen1549 2018-08-23 13:58 采纳率: 100%
浏览 63

如何记录传递给函数的参数的值?

My aim is to create a logging function that lists the name of a function and the list of passed parameters.

An example would be the following:

func MyFunc(a string, b int){

   ... some code ...

   if err != nil{
       errorDescription := myLoggingFunction(err)
       fmt.Println(errorDescription)
   }

}

func main(){
   MyFunc("hello", 42)
}

// where MyLoggingFunction should return something like:   
// "MyFunc: a = hello, b = 42, receivedError = "dummy error description"

So far it seems that in Go there is no way to get the name of the parameters of a function at runtime, as answered in this question, but I could give up this feature.

I've managed to get the function name and the memory address of the passed parameters by analysing the stack trace, but I'm hitting a wall when it comes to print somehow the parameters starting from their address (I understand that it might not be trivial depending on the type of the parameters, but even something very simple will do for now)

This is an implementation of the logging function I'm building (you can test it on this playground), is there away to print the parameter values?

func MyLoggingFunction(err error) string {
    callersPCs := make([]uintptr, 10)
    n := runtime.Callers(2, callersPCs) //skip first 2 entries, (Callers, GetStackTrace)
    callersPCs = callersPCs[:n]

    b := make([]byte, 1000)
    runtime.Stack(b, false)

    stackString := string(b)

    frames := runtime.CallersFrames(callersPCs) 
    frame, _ := frames.Next()

    trimmedString := strings.Split(strings.Split(stackString, "(")[2], ")")[0]
    trimmedString = strings.Replace(trimmedString, " ", "", -1)
    parametersPointers := strings.Split(trimmedString, ",")

    return fmt.Sprintf("Name: %s 
Parameters: %s 
Received Error: %s", frame.Function, parametersPointers, err.Error())
}

If there are other ideas for building such logging function without analysing the stack trace, except the one that consists in passing a map[string]interface{} containing all the passed parameter names as keys and their values as values (that is my current implementation and is tedious since I'd like to log errors very often), I'd be glad to read them.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 腾讯企业邮箱邮件可以恢复么
    • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
    • ¥15 错误 LNK2001 无法解析的外部符号
    • ¥50 安装pyaudiokits失败
    • ¥15 计组这些题应该咋做呀
    • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
    • ¥15 让node服务器有自动加载文件的功能
    • ¥15 jmeter脚本回放有的是对的有的是错的
    • ¥15 r语言蛋白组学相关问题
    • ¥15 Python时间序列如何拟合疏系数模型