Files
EdgeAdmin/internal/apps/log_writer.go

110 lines
2.2 KiB
Go
Raw Normal View History

2020-07-22 09:59:40 +08:00
package apps
import (
"log"
2022-04-10 15:58:54 +08:00
"os"
"runtime"
"strconv"
"strings"
2024-07-27 15:42:58 +08:00
"github.com/TeaOSLab/EdgeAdmin/internal/goman"
"github.com/TeaOSLab/EdgeAdmin/internal/utils/sizes"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/files"
timeutil "github.com/iwind/TeaGo/utils/time"
2020-07-22 09:59:40 +08:00
)
type LogWriter struct {
2022-04-10 15:58:54 +08:00
fp *os.File
c chan string
2020-07-22 09:59:40 +08:00
}
func (this *LogWriter) Init() {
// 创建目录
2022-04-10 15:58:54 +08:00
var dir = files.NewFile(Tea.LogDir())
2020-07-22 09:59:40 +08:00
if !dir.Exists() {
err := dir.Mkdir()
if err != nil {
2022-04-10 15:58:54 +08:00
log.Println("[LOG]create log dir failed: " + err.Error())
2020-07-22 09:59:40 +08:00
}
}
// 打开要写入的日志文件
2022-04-10 15:58:54 +08:00
var logPath = Tea.LogFile("run.log")
fp, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
2020-07-22 09:59:40 +08:00
if err != nil {
2022-04-10 15:58:54 +08:00
log.Println("[LOG]open log file failed: " + err.Error())
2020-07-22 09:59:40 +08:00
} else {
2022-04-10 15:58:54 +08:00
this.fp = fp
}
this.c = make(chan string, 1024)
// 异步写入文件
var maxFileSize = 2 * sizes.G // 文件最大尺寸,超出此尺寸则清空
if fp != nil {
goman.New(func() {
var totalSize int64 = 0
stat, err := fp.Stat()
if err == nil {
totalSize = stat.Size()
}
for message := range this.c {
totalSize += int64(len(message))
_, err := fp.WriteString(timeutil.Format("Y/m/d H:i:s ") + message + "\n")
if err != nil {
log.Println("[LOG]write log failed: " + err.Error())
} else {
// 如果太大则Truncate
if totalSize > maxFileSize {
_ = fp.Truncate(0)
totalSize = 0
}
}
}
})
2020-07-22 09:59:40 +08:00
}
}
func (this *LogWriter) Write(message string) {
2022-04-10 15:58:54 +08:00
backgroundEnv, _ := os.LookupEnv("EdgeBackground")
if backgroundEnv != "on" {
// 文件和行号
var file string
var line int
if Tea.IsTesting() {
var callDepth = 3
var ok bool
_, file, line, ok = runtime.Caller(callDepth)
if ok {
file = this.packagePath(file)
}
}
2020-07-22 09:59:40 +08:00
2022-04-10 15:58:54 +08:00
if len(file) > 0 {
log.Println(message + " (" + file + ":" + strconv.Itoa(line) + ")")
} else {
log.Println(message)
2020-07-22 09:59:40 +08:00
}
}
2022-04-10 15:58:54 +08:00
this.c <- message
2020-07-22 09:59:40 +08:00
}
func (this *LogWriter) Close() {
2022-04-10 15:58:54 +08:00
if this.fp != nil {
_ = this.fp.Close()
}
close(this.c)
}
func (this *LogWriter) packagePath(path string) string {
var pieces = strings.Split(path, "/")
if len(pieces) >= 2 {
return strings.Join(pieces[len(pieces)-2:], "/")
2020-07-22 09:59:40 +08:00
}
2022-04-10 15:58:54 +08:00
return path
2020-07-22 09:59:40 +08:00
}