Skip to content

Commit 4904511

Browse files
feat: log execution file:line
1 parent 2f8c881 commit 4904511

File tree

3 files changed

+26
-7
lines changed

3 files changed

+26
-7
lines changed

_examples/debug/hello_world.go

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package main
2+
3+
func helloworld() {
4+
d("hello, %s", "world")
5+
}

_examples/debug/main.go

+1-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package main
22

33
import (
4-
"net/http"
54
_ "net/http/pprof"
65

76
"go.inout.gg/foundations/debug"
@@ -10,9 +9,5 @@ import (
109
var d = debug.Debuglog("main")
1110

1211
func main() {
13-
d("hello, %s", "world")
14-
15-
if err := http.ListenAndServe(":3000", nil); err != nil {
16-
panic(err)
17-
}
12+
helloworld()
1813
}

debug/debuglog.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ package debug
55
import (
66
"fmt"
77
"os"
8+
"path/filepath"
9+
"runtime"
810
)
911

1012
// Debuglog creates a print function that prints a message to stdout.
@@ -16,6 +18,23 @@ import (
1618
func Debuglog(tag string) func(string, ...any) {
1719
return func(m string, args ...any) {
1820
pid := os.Getpid()
19-
fmt.Println(fmt.Sprintf("%s %d: %s", tag, pid, fmt.Sprintf(m, args...)))
21+
22+
var pcs [1]uintptr
23+
runtime.Callers(2, pcs[:]) // skip [Debuglog, closure]
24+
cf := runtime.CallersFrames([]uintptr{pcs[0]})
25+
f, _ := cf.Next()
26+
27+
var caller string
28+
if f.File != "" {
29+
file, line := f.File, f.Line
30+
caller = format(file, line)
31+
}
32+
33+
fmt.Println(fmt.Sprintf("%s %d [%s]: %s", tag, pid, caller, fmt.Sprintf(m, args...)))
2034
}
2135
}
36+
37+
func format(file string, line int) string {
38+
dir, file := filepath.Split(file)
39+
return fmt.Sprintf("%s:%d", filepath.Join(filepath.Base(dir), file), line)
40+
}

0 commit comments

Comments
 (0)