Skip to content

Commit 4d77464

Browse files
author
小草
authored
日志输出函数名 (#24)
feat: 日志输出增加方法名
1 parent a718986 commit 4d77464

File tree

3 files changed

+15
-11
lines changed

3 files changed

+15
-11
lines changed

examples/custom-logger/logger.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"os"
6+
"path/filepath"
67
"runtime"
78
"strings"
89
"time"
@@ -76,11 +77,11 @@ func (f FileLogger) Sync() error {
7677
}
7778

7879
func output(v ...interface{}) string {
79-
_, file, line, _ := runtime.Caller(3)
80-
files := strings.Split(file, "/")
81-
file = files[len(files)-1]
80+
pc, file, line, _ := runtime.Caller(3)
81+
file = filepath.Base(file)
82+
funcName := strings.TrimPrefix(filepath.Ext(runtime.FuncForPC(pc).Name()), ".")
8283

83-
logFormat := "%s %s:%d " + fmt.Sprint(v...) + "\n"
84+
logFormat := "%s %s:%d:%s " + fmt.Sprint(v...) + "\n"
8485
date := time.Now().Format("2006-01-02 15:04:05")
85-
return fmt.Sprintf(logFormat, date, file, line)
86+
return fmt.Sprintf(logFormat, date, file, line, funcName)
8687
}

examples/custom-logger/logger_test.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66

77
func TestFileLogger_Debug(t *testing.T) {
88
l, err := New("./", DebugLevel)
9-
t.Error(err)
9+
if err != nil {
10+
t.Error(err)
11+
}
1012
l.Debug("abc")
1113
}

log/console.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package log
22

33
import (
44
"fmt"
5+
"path/filepath"
56
"runtime"
67
"strings"
78
"time"
@@ -58,11 +59,11 @@ func (consoleLogger) Sync() error {
5859
}
5960

6061
func output(level string, v ...interface{}) {
61-
_, file, line, _ := runtime.Caller(3)
62-
files := strings.Split(file, "/")
63-
file = files[len(files)-1]
62+
pc, file, line, _ := runtime.Caller(3)
63+
file = filepath.Base(file)
64+
funcName := strings.TrimPrefix(filepath.Ext(runtime.FuncForPC(pc).Name()), ".")
6465

65-
logFormat := "[%s] %s %s:%d " + fmt.Sprint(v...) + "\n"
66+
logFormat := "[%s] %s %s:%d:%s " + fmt.Sprint(v...) + "\n"
6667
date := time.Now().Format("2006-01-02 15:04:05")
67-
fmt.Printf(logFormat, level, date, file, line)
68+
fmt.Printf(logFormat, level, date, file, line, funcName)
6869
}

0 commit comments

Comments
 (0)