Last active
January 18, 2016 19:29
-
-
Save localhots/b020da0739b94583166e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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