Skip to content

Instantly share code, notes, and snippets.

@localhots
Last active January 18, 2016 19:29
Show Gist options
  • Save localhots/b020da0739b94583166e to your computer and use it in GitHub Desktop.
Save localhots/b020da0739b94583166e to your computer and use it in GitHub Desktop.
package main
import (
"log"
"runtime"
"strings"
)
const (
rootPath = "/path/to/project/root/"
)
func foo() {
logWithCaller("test")
}
// Example output:
// 2016/01/18 22:27:42 log_with_caller.go:14:foo test
func logWithCaller(str string) {
pc, file, line, ok := runtime.Caller(1)
if !ok {
log.Println("ERROR: Failed to determine caller")
return
}
fn := runtime.FuncForPC(pc)
if fn == nil {
log.Println("ERROR: Failed to find caller function")
return
}
file = strings.Replace(file, rootPath, "", 1)
fnName := strings.Split(fn.Name(), ".")[1]
log.Printf("%s:%d:%s %s\n", file, line, fnName, str)
}
func main() {
log.SetFlags(log.Ldate | log.Ltime)
foo()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment