feat(logging): 增加 Seq 日志集成与标准输出重定向
- 新增 SeqWriter 支持,将日志异步推送到 Seq 平台,支持多进程实例区分 - 实现 redirectStdout 函数,重定向 os.Stdout 和标准 log 包输出,确保 fmt.Println 等输出被捕获并记录 - 更新 README 文档,增加 Seq 日志集成的说明与配置链接 - 扩展 Logger 结构,支持动态添加输出目标,提升日志记录灵活性
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
package hotime
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"database/sql"
|
||||
"io/ioutil"
|
||||
stdlog "log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -340,6 +343,16 @@ func (that *Application) SetConfig(configPath ...string) {
|
||||
that.WebConnectLog = log.NewLoggerNoCaller(1, that.Config.GetString("webConnectLogFile"), 0)
|
||||
}
|
||||
|
||||
// 重定向 os.Stdout 和标准 log 包,捕获 fmt.Println 等绕过 HoTime Logger 的输出
|
||||
redirectStdout(that.Log)
|
||||
|
||||
// 接入 Seq:instance = ip:port,同机多进程靠端口区分,跨机器靠 IP 区分
|
||||
if seqUrl := that.Config.GetString("seqUrl"); seqUrl != "" {
|
||||
instance := getLocalIP() + ":" + that.Config.GetString("port")
|
||||
that.Log.SetSeqWriter(seqUrl, that.Config.GetString("seqApiKey"), instance)
|
||||
that.Log.Infof("Seq 日志推送已启动: url=%s instance=%s", seqUrl, instance)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// SetConnectListener 连接判断,返回false继续传输至控制层,true则停止传输
|
||||
@@ -623,6 +636,42 @@ func (that *Application) crossDomain(context *Context, sessionId string) {
|
||||
|
||||
}
|
||||
|
||||
// getLocalIP 通过 UDP dial 探测方式获取本机出口 IP(不发送任何数据,无副作用)。
|
||||
// 用于构建 Seq instance 字段,格式为 ip:port,支持跨机器集群识别。
|
||||
// 失败时返回 "unknown"。
|
||||
func getLocalIP() string {
|
||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
defer conn.Close()
|
||||
return conn.LocalAddr().(*net.UDPAddr).IP.String()
|
||||
}
|
||||
|
||||
// redirectStdout 重定向 os.Stdout 和标准 log 包到 HoTime Logger。
|
||||
// 捕获 fmt.Println/fmt.Printf 等绕过 HoTime 日志系统的输出,
|
||||
// 以 INFO 级别 + source="stdout" 字段写入,后续经 SeqWriter 推送到 Seq。
|
||||
func redirectStdout(l *log.Logger) {
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
os.Stdout = w
|
||||
stdlog.SetOutput(w)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(r)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line != "" {
|
||||
l.Info().Str("source", "stdout").Msg(line)
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
l.Errorf("[stdout redirect] scanner error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Init 初始化application
|
||||
func Init(config string) *Application {
|
||||
appIns := Application{}
|
||||
|
||||
Reference in New Issue
Block a user