Skip to content

Commit

Permalink
Output method name in log (#5322)
Browse files Browse the repository at this point in the history
Signed-off-by: Changxin Miao <[email protected]>
  • Loading branch information
polyrabbit authored Nov 26, 2024
1 parent c802d12 commit 7721e54
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
31 changes: 30 additions & 1 deletion pkg/utils/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,14 @@ func (l *logHandle) Format(e *logrus.Entry) ([]byte, error) {
}
const timeFormat = "2006/01/02 15:04:05.000000"
timestamp := e.Time.Format(timeFormat)
str := fmt.Sprintf("%s%v %s[%d] <%v>: %v [%s:%d]",
str := fmt.Sprintf("%s%v %s[%d] <%v>: %v [%s@%s:%d]",
l.logid,
timestamp,
l.name,
os.Getpid(),
lvlStr,
strings.TrimRight(e.Message, "\n"),
methodName(e.Caller.Function),
path.Base(e.Caller.File),
e.Caller.Line)

Expand All @@ -80,6 +81,34 @@ func (l *logHandle) Format(e *logrus.Entry) ([]byte, error) {
return []byte(str), nil
}

// Returns a human-readable method name, removing internal markers added by Go
func methodName(fullFuncName string) string {
firstSlash := strings.Index(fullFuncName, "/")
if firstSlash != -1 && firstSlash < len(fullFuncName)-1 {
fullFuncName = fullFuncName[firstSlash+1:]
}
lastDot := strings.LastIndex(fullFuncName, ".")
if lastDot == -1 || lastDot == len(fullFuncName)-1 {
return fullFuncName
}
method := fullFuncName[lastDot+1:]
// avoid func1
if strings.HasPrefix(method, "func") && method[4] >= '0' && method[4] <= '9' {
candidate := methodName(fullFuncName[:lastDot])
if candidate != "" {
method = candidate
}
}
// aoid init.3
if len(method) == 1 && method[0] >= '0' && method[0] <= '9' {
candidate := methodName(fullFuncName[:lastDot])
if candidate != "" {
method = candidate
}
}
return method
}

// for aws.Logger
func (l *logHandle) Log(args ...interface{}) {
l.Debugln(args...)
Expand Down
36 changes: 36 additions & 0 deletions pkg/utils/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,39 @@ func TestLogger(t *testing.T) {
t.Fatalf("logid \"testid\" should be logged: %s", s)
}
}

func TestMethodName(t *testing.T) {
type args struct {
fullFuncName string
}
tests := []struct {
name string
args args
want string
}{{
name: "main",
args: args{
fullFuncName: "cmd.Main",
},
want: "Main",
}, {
name: "nested method",
args: args{
fullFuncName: "github.com/juicedata/juicefs/cmd.watchdog.func1",
},
want: "watchdog",
}, {
name: "multiple inits",
args: args{
fullFuncName: "github.com/juicedata/juicefs/pkg/utils.init.3.func1",
},
want: "init",
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := methodName(tt.args.fullFuncName); got != tt.want {
t.Errorf("methodName() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 7721e54

Please sign in to comment.