sonumb

Go - 현재 함수 이름 받아오기 본문

개발자 이야기/Go

Go - 현재 함수 이름 받아오기

sonumb 2021. 11. 4. 15:49

출처: https://stackoverflow.com/questions/25927660/how-to-get-the-current-function-name

 

How to get the current function name

For tracing purpose, I'd like to print out current function name, like the __FUNCTION__ macro in gcc. So that when I have a function func foo () { trace() } it will automatically print out En...

stackoverflow.com

 

// 반환: 파일이름, 현재라인, 함수이름
func trace() (string, int, string, error) {
    pc, file, line, ok := runtime.Caller(1)
    if ok == false {
      return "?", 0, "?"
    }

    fn := runtime.FuncForPC(pc)
    if fn == nil {
      return file, line, "?"
    }

    return file, line, fn.Name()
}
반응형