在开发环境下运行日志显示包名

This commit is contained in:
GoEdgeLab
2021-11-14 20:31:49 +08:00
parent fff7e7a95d
commit 9fc4bcf25a

View File

@@ -7,9 +7,9 @@ import (
"github.com/iwind/TeaGo/utils/time" "github.com/iwind/TeaGo/utils/time"
"log" "log"
"os" "os"
"path/filepath"
"runtime" "runtime"
"strconv" "strconv"
"strings"
) )
type LogWriter struct { type LogWriter struct {
@@ -38,18 +38,20 @@ func (this *LogWriter) Init() {
} }
func (this *LogWriter) Write(message string) { func (this *LogWriter) Write(message string) {
backgroundEnv, _ := os.LookupEnv("EdgeBackground")
if backgroundEnv != "on" {
// 文件和行号 // 文件和行号
var callDepth = 2
var file string var file string
var line int var line int
if Tea.IsTesting() {
var callDepth = 3
var ok bool var ok bool
_, file, line, ok = runtime.Caller(callDepth) _, file, line, ok = runtime.Caller(callDepth)
if ok { if ok {
file = filepath.Base(file) file = this.packagePath(file)
}
} }
backgroundEnv, _ := os.LookupEnv("EdgeBackground")
if backgroundEnv != "on" {
if len(file) > 0 { if len(file) > 0 {
log.Println(message + " (" + file + ":" + strconv.Itoa(line) + ")") log.Println(message + " (" + file + ":" + strconv.Itoa(line) + ")")
} else { } else {
@@ -70,3 +72,11 @@ func (this *LogWriter) Close() {
_ = this.fileAppender.Close() _ = this.fileAppender.Close()
} }
} }
func (this *LogWriter) packagePath(path string) string {
var pieces = strings.Split(path, "/")
if len(pieces) >= 2 {
return strings.Join(pieces[len(pieces)-2:], "/")
}
return path
}