-
Notifications
You must be signed in to change notification settings - Fork 110
/
caller.go
85 lines (68 loc) · 1.32 KB
/
caller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2021 ChainSafe Systems (ON)
// SPDX-License-Identifier: LGPL-3.0-only
package log
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
type callerSettings struct {
file *bool
line *bool
funC *bool
}
func (c *callerSettings) mergeWith(other callerSettings) {
if other.file != nil {
value := *other.file
c.file = &value
}
if other.line != nil {
value := *other.line
c.line = &value
}
if other.funC != nil {
value := *other.funC
c.funC = &value
}
// Keep depth to 1
}
func (c *callerSettings) setDefaults() {
if c.file == nil {
value := false
c.file = &value
}
if c.line == nil {
value := false
c.line = &value
}
if c.funC == nil {
value := false
c.funC = &value
}
}
func getCallerString(settings callerSettings) (s string) {
if !*settings.file && !*settings.line && !*settings.funC {
return ""
}
const depth = 3
pc, file, line, ok := runtime.Caller(depth)
if !ok {
return "error"
}
var fields []string
if *settings.file {
fields = append(fields, filepath.Base(file))
}
if *settings.line {
fields = append(fields, "L"+fmt.Sprint(line))
}
if *settings.funC {
details := runtime.FuncForPC(pc)
if details != nil {
funcName := strings.TrimLeft(filepath.Ext(details.Name()), ".")
fields = append(fields, funcName)
}
}
return strings.Join(fields, ":")
}