新增实例槽位隔离与结构化日志,多开不再共用日志与账号
This commit is contained in:
+158
-173
@@ -7,12 +7,13 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
"huya-go/internal/instance"
|
||||
"huya-go/internal/logger"
|
||||
"huya-go/internal/sniper"
|
||||
)
|
||||
|
||||
@@ -20,25 +21,31 @@ const (
|
||||
eventLog = "gui:log"
|
||||
eventMonitorResult = "gui:monitor-result"
|
||||
eventMonitorState = "gui:monitor-state"
|
||||
maxLogEntries = 500
|
||||
logQueueSize = 2048
|
||||
|
||||
// maxLogEntries 内存里保留的日志条数,界面按自增 ID 增量拉取。
|
||||
maxLogEntries = 2000
|
||||
|
||||
// 日志分类,便于在界面上区分应用、网络、监控与账号维度的日志。
|
||||
categoryApp = "应用"
|
||||
categoryNet = "网络"
|
||||
categoryMonitor = "监控"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
ctx context.Context
|
||||
|
||||
logMu sync.Mutex
|
||||
logs []LogEntry
|
||||
// logStore 是内存日志缓冲;界面通过 GetLogs(sinceID) 增量拉取。
|
||||
logStore *logger.Store
|
||||
// closeLog 由 logger.Init 返回,用于在退出时把异步队列刷盘。
|
||||
closeLog func()
|
||||
logInitErr error
|
||||
|
||||
logCh chan LogEntry
|
||||
logStop chan struct{}
|
||||
logWorkerOnce sync.Once
|
||||
logStopOnce sync.Once
|
||||
droppedLogs atomic.Int64
|
||||
// logSink 为 nil 表示当前环境无法写日志文件,日志只留在内存与界面上。
|
||||
logSink *logSink
|
||||
logSinkErr error
|
||||
logWriteFailures atomic.Int64
|
||||
// instanceLease 在 wails.Run 之前由 main 占用并注入(WebView2 目录需要提前确定)。
|
||||
instanceLease *instance.Lease
|
||||
instanceErr error
|
||||
instanceName string
|
||||
instanceID string
|
||||
dataDir string
|
||||
|
||||
runMu sync.Mutex
|
||||
monitorCancel context.CancelFunc
|
||||
@@ -80,13 +87,22 @@ type AccountPreview struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type LogEntry struct {
|
||||
Time string `json:"time"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
// LogStats 描述当前日志运行时状态,供界面展示与排查。
|
||||
type LogStats struct {
|
||||
Level string `json:"level"`
|
||||
FilePath string `json:"filePath"`
|
||||
Dir string `json:"dir"`
|
||||
Dropped uint64 `json:"dropped"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// at 只用于落盘,保证文件里带完整日期(不参与 JSON 序列化)。
|
||||
at time.Time
|
||||
// InstanceInfo 描述当前进程占用的实例,供界面展示与本地存储分片。
|
||||
type InstanceInfo struct {
|
||||
Name string `json:"name"`
|
||||
ID string `json:"id"`
|
||||
DataDir string `json:"dataDir"`
|
||||
LogDir string `json:"logDir"`
|
||||
LogFile string `json:"logFile"`
|
||||
}
|
||||
|
||||
type PrizeListResult struct {
|
||||
@@ -129,58 +145,140 @@ type cookieLine struct {
|
||||
text string
|
||||
}
|
||||
|
||||
func NewApp() *App {
|
||||
app := &App{
|
||||
logCh: make(chan LogEntry, logQueueSize),
|
||||
logStop: make(chan struct{}),
|
||||
}
|
||||
// 日志文件不可用时只降级为内存日志,不影响主流程。
|
||||
sink, err := newLogSink()
|
||||
if err != nil {
|
||||
app.logSinkErr = err
|
||||
} else {
|
||||
app.logSink = sink
|
||||
}
|
||||
return app
|
||||
// NewApp 创建 App 实例。lease 由 main 在 wails.Run 之前占用并注入。
|
||||
//
|
||||
// 为什么要在 wails.Run 之前占位:WebView2 的用户数据目录必须在创建窗口之前确定,
|
||||
// 而它必须按实例区分(见 instance.Lease.WebviewUserDataDir)。
|
||||
// 用构造器参数而不是导出的 setter,是为了避免它被 Wails 当成前端可调用方法生成绑定。
|
||||
func NewApp(lease *instance.Lease, instanceErr error) *App {
|
||||
return &App{instanceLease: lease, instanceErr: instanceErr}
|
||||
}
|
||||
|
||||
func (a *App) Startup(ctx context.Context) {
|
||||
a.ctx = ctx
|
||||
a.startLogWorker()
|
||||
a.addLog("info", "GUI 已启动")
|
||||
if a.logSink != nil {
|
||||
a.addLog("info", "日志文件: %s", a.logSink.Path())
|
||||
} else if a.logSinkErr != nil {
|
||||
a.addLog("warn", "日志文件不可用,日志仅保留在界面: %v", a.logSinkErr)
|
||||
|
||||
lease, leaseErr := a.instanceLease, a.instanceErr
|
||||
if lease == nil {
|
||||
// 其它入口(测试、非 Wails 启动)没有提前占位时在这里补一次。
|
||||
lease, leaseErr = instance.Acquire()
|
||||
}
|
||||
logDir := ""
|
||||
if lease != nil {
|
||||
a.instanceLease = lease
|
||||
a.instanceName = lease.Name()
|
||||
a.instanceID = lease.ID()
|
||||
a.dataDir = lease.Paths().DataDir
|
||||
logDir = lease.Paths().LogDir
|
||||
}
|
||||
if a.instanceName == "" {
|
||||
a.instanceName = "默认实例"
|
||||
}
|
||||
if a.instanceID == "" {
|
||||
a.instanceID = "default"
|
||||
}
|
||||
|
||||
a.logStore = logger.NewStore(maxLogEntries)
|
||||
// 日志先注册界面推送,再初始化文件输出,这样启动阶段的日志也能实时到达界面。
|
||||
logger.SetEmitter(func(entry logger.Entry) {
|
||||
a.emit(eventLog, entry)
|
||||
})
|
||||
closeLog, logErr := logger.Init(a.logStore, logDir, a.instanceName, a.instanceID, a.dataDir)
|
||||
a.closeLog = closeLog
|
||||
a.logInitErr = logErr
|
||||
|
||||
if leaseErr != nil {
|
||||
// 数据目录仍然是本实例独享的(临时实例),但隔离能力已降级,必须让人看见。
|
||||
logger.LogEvent("系统", logger.LevelWarn, "实例隔离已降级(%s,数据目录仍独立): %v", a.instanceName, leaseErr)
|
||||
} else {
|
||||
logger.LogEvent("系统", logger.LevelSuccess, "已启动%s,数据目录: %s", a.instanceName, a.dataDir)
|
||||
}
|
||||
if logErr != nil {
|
||||
logger.LogEvent(categoryApp, logger.LevelWarn, "日志文件不可用,日志仅保留在界面: %v", logErr)
|
||||
}
|
||||
}
|
||||
|
||||
// GetLogFilePath 返回当前日志文件路径(供界面展示/复制)。
|
||||
func (a *App) GetLogFilePath() string {
|
||||
if a.logSink == nil {
|
||||
return ""
|
||||
return logger.FilePath()
|
||||
}
|
||||
|
||||
// GetLogs 返回自增 ID 大于 sinceID 的日志,界面据此增量拉取。
|
||||
func (a *App) GetLogs(sinceID int64) []logger.Entry {
|
||||
if a.logStore == nil {
|
||||
return []logger.Entry{}
|
||||
}
|
||||
return a.logSink.Path()
|
||||
return a.logStore.Since(sinceID)
|
||||
}
|
||||
|
||||
// GetLogStats 返回日志运行时状态(等级、文件、丢弃条数)。
|
||||
func (a *App) GetLogStats() LogStats {
|
||||
return LogStats{
|
||||
Level: logger.MinLevel(),
|
||||
FilePath: logger.FilePath(),
|
||||
Dir: logger.Dir(),
|
||||
Dropped: logger.Dropped(),
|
||||
Count: a.logStoreCount(),
|
||||
}
|
||||
}
|
||||
|
||||
// SetLogLevel 调整日志最低输出等级,返回归一化后的等级。
|
||||
func (a *App) SetLogLevel(level string) string {
|
||||
normalized := logger.LevelFromString(level)
|
||||
logger.SetMinLevel(normalized)
|
||||
logger.LogEvent(categoryApp, logger.LevelSuccess, "日志等级已切换为 %s", normalized)
|
||||
return normalized
|
||||
}
|
||||
|
||||
// GetInstanceInfo 返回当前实例信息(名称、标识、数据与日志路径)。
|
||||
func (a *App) GetInstanceInfo() InstanceInfo {
|
||||
name := a.instanceName
|
||||
if name == "" {
|
||||
name = "默认实例"
|
||||
}
|
||||
id := a.instanceID
|
||||
if id == "" {
|
||||
id = "default"
|
||||
}
|
||||
info := InstanceInfo{Name: name, ID: id, DataDir: a.dataDir, LogFile: logger.FilePath()}
|
||||
if a.instanceLease != nil {
|
||||
info.LogDir = a.instanceLease.Paths().LogDir
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// OpenLogDir 用系统文件管理器打开日志目录。
|
||||
func (a *App) OpenLogDir() error {
|
||||
if a.logSink == nil {
|
||||
if a.logSinkErr != nil {
|
||||
return fmt.Errorf("日志目录不可用: %w", a.logSinkErr)
|
||||
dir := logger.Dir()
|
||||
if dir == "" {
|
||||
if a.logInitErr != nil {
|
||||
return fmt.Errorf("日志目录不可用: %w", a.logInitErr)
|
||||
}
|
||||
return errors.New("日志目录不可用")
|
||||
}
|
||||
if err := openDirectory(a.logSink.Dir()); err != nil {
|
||||
if err := openDirectory(dir); err != nil {
|
||||
return fmt.Errorf("打开日志目录失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) logStoreCount() int {
|
||||
if a.logStore == nil {
|
||||
return 0
|
||||
}
|
||||
return a.logStore.Count()
|
||||
}
|
||||
|
||||
func (a *App) Shutdown(ctx context.Context) {
|
||||
a.StopMonitor()
|
||||
a.stopLogWorker()
|
||||
a.closeLogSink()
|
||||
logger.SetEmitter(nil)
|
||||
if a.closeLog != nil {
|
||||
a.closeLog()
|
||||
a.closeLog = nil
|
||||
}
|
||||
if a.instanceLease != nil {
|
||||
a.instanceLease.Release()
|
||||
a.instanceLease = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) DefaultConfig() Config {
|
||||
@@ -218,12 +316,6 @@ func (a *App) PreviewAccounts(cookieText string) []AccountPreview {
|
||||
return previews
|
||||
}
|
||||
|
||||
func (a *App) GetLogs() []LogEntry {
|
||||
a.logMu.Lock()
|
||||
defer a.logMu.Unlock()
|
||||
return append([]LogEntry(nil), a.logs...)
|
||||
}
|
||||
|
||||
func (a *App) IsRunning() bool {
|
||||
a.runMu.Lock()
|
||||
defer a.runMu.Unlock()
|
||||
@@ -400,7 +492,8 @@ func (a *App) StartMonitor(cfg Config) error {
|
||||
runner := sniper.Runner{Client: client}
|
||||
emit := func(result sniper.Result) {
|
||||
a.emit(eventMonitorResult, result)
|
||||
a.addLog("info", "监控结果: loop=%d uid=%d action=%s category=%s msg=%s error=%s", result.Loop, result.UID, result.Action, result.Category, result.Message, result.Error)
|
||||
a.logAccount(categoryMonitor, sniper.LogLevelForCategory(result.Category), strconv.FormatInt(result.UID, 10),
|
||||
"loop=%d action=%s category=%s msg=%s error=%s", result.Loop, result.Action, result.Category, result.Message, result.Error)
|
||||
}
|
||||
runnerCfg := sniper.Config{
|
||||
SID: cfg.SID,
|
||||
@@ -451,9 +544,10 @@ func (a *App) StopMonitor() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// newClient 创建活动客户端,并把逐条网络交互接到 debug 级日志。
|
||||
func (a *App) newClient(cfg Config) (huya.ActivityClient, func(), error) {
|
||||
return huya.NewActivityClient(cfg.Transport, cfg.WSSHost, time.Duration(cfg.TimeoutSec)*time.Second, func(msg string) {
|
||||
a.addLog("debug", "%s", msg)
|
||||
a.logEvent(categoryNet, logger.LevelDebug, "%s", msg)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -484,128 +578,19 @@ func (a *App) finishMonitor(message string) {
|
||||
a.emitState(false, message)
|
||||
}
|
||||
|
||||
// addLog 记录一条应用级日志。
|
||||
func (a *App) addLog(level, format string, args ...any) {
|
||||
now := time.Now()
|
||||
entry := LogEntry{
|
||||
Time: now.Format("15:04:05.000"),
|
||||
at: now,
|
||||
Level: level,
|
||||
Message: fmt.Sprintf(format, args...),
|
||||
}
|
||||
if a.logCh == nil {
|
||||
a.writeLogEntry(entry)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case a.logCh <- entry:
|
||||
default:
|
||||
a.droppedLogs.Add(1)
|
||||
}
|
||||
logger.LogEvent(categoryApp, level, format, args...)
|
||||
}
|
||||
|
||||
func (a *App) startLogWorker() {
|
||||
if a.logCh == nil {
|
||||
a.logCh = make(chan LogEntry, logQueueSize)
|
||||
}
|
||||
if a.logStop == nil {
|
||||
a.logStop = make(chan struct{})
|
||||
}
|
||||
a.logWorkerOnce.Do(func() {
|
||||
go a.logWorker()
|
||||
})
|
||||
// logEvent 记录一条带分类的日志。
|
||||
func (a *App) logEvent(category, level, format string, args ...any) {
|
||||
logger.LogEvent(category, level, format, args...)
|
||||
}
|
||||
|
||||
func (a *App) stopLogWorker() {
|
||||
if a.logStop == nil {
|
||||
return
|
||||
}
|
||||
a.logStopOnce.Do(func() {
|
||||
close(a.logStop)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) logWorker() {
|
||||
for {
|
||||
select {
|
||||
case entry := <-a.logCh:
|
||||
a.flushDroppedLogs()
|
||||
a.writeLogEntry(entry)
|
||||
case <-a.logStop:
|
||||
a.drainLogQueue()
|
||||
a.flushDroppedLogs()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) drainLogQueue() {
|
||||
for {
|
||||
select {
|
||||
case entry := <-a.logCh:
|
||||
a.flushDroppedLogs()
|
||||
a.writeLogEntry(entry)
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) flushDroppedLogs() {
|
||||
dropped := a.droppedLogs.Swap(0)
|
||||
if dropped <= 0 {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
a.writeLogEntry(LogEntry{
|
||||
Time: now.Format("15:04:05.000"),
|
||||
at: now,
|
||||
Level: "warn",
|
||||
Message: fmt.Sprintf("日志队列繁忙,已异步丢弃 %d 条日志", dropped),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) writeLogEntry(entry LogEntry) {
|
||||
a.emitLogEntry(entry, true)
|
||||
}
|
||||
|
||||
// emitLogEntry 写入内存缓存并推给界面;persist 为 true 时同时落盘。
|
||||
func (a *App) emitLogEntry(entry LogEntry, persist bool) {
|
||||
a.logMu.Lock()
|
||||
a.logs = append(a.logs, entry)
|
||||
if len(a.logs) > maxLogEntries {
|
||||
a.logs = append([]LogEntry(nil), a.logs[len(a.logs)-maxLogEntries:]...)
|
||||
}
|
||||
a.logMu.Unlock()
|
||||
a.emit(eventLog, entry)
|
||||
if persist {
|
||||
a.appendLogFile(entry)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) appendLogFile(entry LogEntry) {
|
||||
sink := a.logSink
|
||||
if sink == nil {
|
||||
return
|
||||
}
|
||||
if err := sink.Write(entry); err != nil {
|
||||
// 只在第一次失败时提示,且不再落盘,避免刷屏与递归。
|
||||
if a.logWriteFailures.Add(1) == 1 {
|
||||
now := time.Now()
|
||||
a.emitLogEntry(LogEntry{
|
||||
Time: now.Format("15:04:05.000"),
|
||||
at: now,
|
||||
Level: "warn",
|
||||
Message: fmt.Sprintf("日志写入文件失败,已改为仅界面输出: %v", err),
|
||||
}, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) closeLogSink() {
|
||||
if a.logSink == nil {
|
||||
return
|
||||
}
|
||||
_ = a.logSink.Close()
|
||||
// logAccount 记录一条带账号标签的日志,便于界面按账号观察抢购链路。
|
||||
func (a *App) logAccount(category, level, account string, format string, args ...any) {
|
||||
logger.LogAccountEvent(category, level, account, format, args...)
|
||||
}
|
||||
|
||||
func (a *App) emitState(running bool, message string) {
|
||||
|
||||
Reference in New Issue
Block a user