refactor(logger): 日志改用 logrus 全局包级调用,移除 Logger 注入接口

为什么:并入宿主项目后须与宿主日志体系一致——宿主统一用 pkg/logger 初始化
logrus 全局实例并直接 logrus.Xxx 包级调用;包一层 Logger 接口会让 logrus 的
caller 定位(报告调用文件:行号)失准。

改动:
- 删除 logger 包(Logger 接口 / Default / SetDefault,默认本就是 logrus.StandardLogger)
- 11 个结构体移除 lgr logger.Logger 字段、SetLogger 方法及构造中的 lgr 初始化
- 192 处 lgr.Xxxf 调用改为 logrus.Xxxf,日志消息文本保持不变
- xiaomi.Client 移除 Logger() 访问器,air_conditioner 回读日志去掉判空调用直连 logrus
- miot_i18n.go 两处标准库 log.Printf 改为 logrus.Errorf,统一日志出口
- go.mod:logrus 从 indirect 提升为直接依赖
- goimports/goformat 全树规范化:此前部分文件未 gofmt(单行 if、对齐),本次顺带
  格式化,纯空白/换行变化,无逻辑改动

验证:go build / go vet / go test ./... 全部通过(bridge、miot、xiaomi、devices、specs)
This commit is contained in:
2026-09-15 20:16:26 +08:00
parent 7ae32bd012
commit 2b7de69403
46 changed files with 1166 additions and 903 deletions
+46 -52
View File
@@ -9,7 +9,7 @@ import (
"sync"
"time"
"xiaomihome/logger"
"github.com/sirupsen/logrus"
)
// ============================================================================
@@ -101,8 +101,6 @@ type MIoTClient struct {
mu sync.RWMutex
refreshMu sync.Mutex // token 刷新互斥锁
// === Logger ===
lgr logger.Logger
}
// NewMIoTClient creates a new MIoTClient.
@@ -129,14 +127,10 @@ func NewMIoTClient(entryID string, entryData map[string]interface{}, uid string,
mipsLocalStateTimers: make(map[string]*time.Timer),
ctx: ctx,
cancel: cancel,
lgr: logger.Default(),
}
return c
}
// SetLogger sets a custom logger for MIoTClient.
func (c *MIoTClient) SetLogger(l logger.Logger) { c.lgr = l }
// Init initializes the MIoTClient.
// Aligns with Python MIoTClient.init_async.
func (c *MIoTClient) Init() error {
@@ -156,7 +150,7 @@ func (c *MIoTClient) Init() error {
if et, ok := authInfo["expires_ts"].(float64); ok {
c.entryData["expires_ts"] = et
}
c.lgr.Debugf("[MIoTClient] Loaded token from storage\n")
logrus.Debugf("[MIoTClient] Loaded token from storage\n")
} else if accessToken != "" {
// First run: write entryData token to storage
expiresTS := float64(time.Now().Unix()) + 3600*24*30 // default 30 days
@@ -168,7 +162,7 @@ func (c *MIoTClient) Init() error {
"refresh_token": refreshToken,
"expires_ts": expiresTS,
}, true)
c.lgr.Debugf("[MIoTClient] Saved initial token to storage\n")
logrus.Debugf("[MIoTClient] Saved initial token to storage\n")
}
}
@@ -179,7 +173,7 @@ func (c *MIoTClient) Init() error {
// 2. Load device cache
if err := c.loadCacheDevice(); err != nil {
c.lgr.Warnf("[MIoTClient] Warning: failed to load device cache: %v\n", err)
logrus.Warnf("[MIoTClient] Warning: failed to load device cache: %v\n", err)
}
// 3.1 Initialize OAuth client
@@ -187,27 +181,27 @@ func (c *MIoTClient) Init() error {
oauthRedirectURL, _ := c.entryData["oauth_redirect_url"].(string)
uuid, _ := c.entryData["uuid"].(string)
c.oauth = NewMIoTOauthClient(OAUTH2_CLIENT_ID, oauthRedirectURL, c.cloudServer, uuid)
c.lgr.Debugf("[MIoTClient] OAuth client initialized\n")
logrus.Debugf("[MIoTClient] OAuth client initialized\n")
}
// 3.2 Initialize Cert client
cert, err := NewMIoTCert(c.storage, c.uid, c.cloudServer)
if err != nil {
c.lgr.Warnf("[MIoTClient] Warning: cert init failed: %v\n", err)
logrus.Warnf("[MIoTClient] Warning: cert init failed: %v\n", err)
} else {
c.cert = cert
c.cert.VerifyCACert()
c.lgr.Debugf("[MIoTClient] Cert client initialized\n")
logrus.Debugf("[MIoTClient] Cert client initialized\n")
}
// 4. Initialize HTTP client (use token from storage if available)
if c.http == nil && accessToken != "" {
httpClient, err := NewMIoTHttpClient(c.cloudServer, OAUTH2_CLIENT_ID, accessToken)
if err != nil {
c.lgr.Warnf("[MIoTClient] Warning: failed to create HTTP client: %v\n", err)
logrus.Warnf("[MIoTClient] Warning: failed to create HTTP client: %v\n", err)
} else {
c.http = httpClient
c.lgr.Debugf("[MIoTClient] HTTP client created\n")
logrus.Debugf("[MIoTClient] HTTP client created\n")
}
}
@@ -223,9 +217,9 @@ func (c *MIoTClient) Init() error {
// Connect asynchronously to not block Init
c.mu.Unlock()
if err := mips.Connect(); err != nil {
c.lgr.Warnf("[MIoTClient] Warning: MIPS cloud connect failed: %v\n", err)
logrus.Warnf("[MIoTClient] Warning: MIPS cloud connect failed: %v\n", err)
} else {
c.lgr.Debugf("[MIoTClient] MIPS cloud connected\n")
logrus.Debugf("[MIoTClient] MIPS cloud connected\n")
}
c.mu.Lock()
}
@@ -239,7 +233,7 @@ func (c *MIoTClient) Init() error {
nw.SubNetworkStatus(key, c.onNetworkStatusChanged)
status := nw.GetNetworkStatus()
c.onNetworkStatusChanged(status)
c.lgr.Debugf("[MIoTClient] Network status subscribed (online=%v)\n", status)
logrus.Debugf("[MIoTClient] Network status subscribed (online=%v)\n", status)
}
}
@@ -258,12 +252,12 @@ func (c *MIoTClient) Init() error {
groupID, _ := info["group_id"].(string)
if groupID != "" {
svc.SubServiceChange(key, groupID, c.onMipsServiceStateChange)
c.lgr.Debugf("[MIoTClient] mDNS service subscribed: home=%s, group=%s\n", homeID, groupID)
logrus.Debugf("[MIoTClient] mDNS service subscribed: home=%s, group=%s\n", homeID, groupID)
// Check if service already discovered
serviceData := svc.GetServices(groupID)
if sd, exists := serviceData[groupID]; exists && sd.validService() {
c.lgr.Debugf("[MIoTClient] Central mips service scanned: %s, %v\n", homeID, sd)
logrus.Debugf("[MIoTClient] Central mips service scanned: %s, %v\n", homeID, sd)
mips := NewMipsLocalClient(
getVirtualDID(c.entryData),
sd.Addresses[0],
@@ -294,7 +288,7 @@ func (c *MIoTClient) Init() error {
if lan.InitDone() {
c.onMiotLanStateChange(true)
}
c.lgr.Debugf("[MIoTClient] LAN control initialized\n")
logrus.Debugf("[MIoTClient] LAN control initialized\n")
}
}
} else {
@@ -324,9 +318,9 @@ func (c *MIoTClient) Init() error {
}
c.i18n = NewMIoTI18n(lang)
c.i18n.Init()
c.lgr.Debugf("[MIoTClient] i18n initialized (lang=%s)\n", lang)
logrus.Debugf("[MIoTClient] i18n initialized (lang=%s)\n", lang)
c.lgr.Infof("[MIoTClient] Initialized\n")
logrus.Infof("[MIoTClient] Initialized\n")
return nil
}
@@ -358,7 +352,7 @@ func (c *MIoTClient) Deinit() error {
if c.mipsCloud != nil {
c.mipsCloud.UnsubState(key)
c.mipsCloud.Disconnect()
c.lgr.Debugf("[MIoTClient] MIPS cloud disconnected\n")
logrus.Debugf("[MIoTClient] MIPS cloud disconnected\n")
}
// 4. Cancel refresh cloud devices timer
@@ -441,9 +435,9 @@ func (c *MIoTClient) Deinit() error {
}
deviceKey := fmt.Sprintf("%s_%s", c.uid, c.cloudServer)
if err := c.storage.Save("miot_devices", deviceKey, deviceListForStorage); err != nil {
c.lgr.Warnf("[MIoTClient] Warning: failed to save devices on deinit: %v\n", err)
logrus.Warnf("[MIoTClient] Warning: failed to save devices on deinit: %v\n", err)
}
c.lgr.Infof("[MIoTClient] Device cache saved to storage\n")
logrus.Infof("[MIoTClient] Device cache saved to storage\n")
}
// Cancel context
@@ -454,7 +448,7 @@ func (c *MIoTClient) Deinit() error {
// Clear subscription tree
c.subTree.Clear()
c.lgr.Infof("[MIoTClient] Deinitialized\n")
logrus.Infof("[MIoTClient] Deinitialized\n")
return nil
}
@@ -493,7 +487,7 @@ func (c *MIoTClient) loadCacheDevice() error {
c.deviceListCache[did] = infoMap
}
}
c.lgr.Debugf("[MIoTClient] Loaded %d devices from cache\n", len(deviceList))
logrus.Debugf("[MIoTClient] Loaded %d devices from cache\n", len(deviceList))
return nil
}
@@ -647,7 +641,7 @@ func (c *MIoTClient) RefreshAuthInfo() (map[string]interface{}, error) {
c.mipsCloud.UpdateAccessToken(ac)
}
c.lgr.Debugf("[MIoTClient] RefreshAuthInfo: token refreshed\n")
logrus.Debugf("[MIoTClient] RefreshAuthInfo: token refreshed\n")
return result, nil
}
@@ -678,7 +672,7 @@ func (c *MIoTClient) refreshUserCert() {
// Verify CA cert
if ok, err := c.cert.VerifyCACert(); err != nil || !ok {
c.lgr.Errorf("[MIoTClient] CA cert verification FAILED: %v\n", err)
logrus.Errorf("[MIoTClient] CA cert verification FAILED: %v\n", err)
}
// Check remaining time
@@ -690,14 +684,14 @@ func (c *MIoTClient) refreshUserCert() {
nextDelay = 60
}
c.RequestRefreshUserCert(nextDelay)
c.lgr.Debugf("[MIoTClient] Cert still valid for %ds, recheck in %ds\n", remainSec, nextDelay)
logrus.Debugf("[MIoTClient] Cert still valid for %ds, recheck in %ds\n", remainSec, nextDelay)
return
}
// Load user key
_, err := c.cert.LoadUserKey()
if err != nil {
c.lgr.Errorf("[MIoTClient] Cert refresh: load key FAILED: %v\n", err)
logrus.Errorf("[MIoTClient] Cert refresh: load key FAILED: %v\n", err)
// Retry after delay
c.RequestRefreshUserCert(3600)
return
@@ -706,7 +700,7 @@ func (c *MIoTClient) refreshUserCert() {
// Generate CSR
csr, err := c.cert.GenUserCSR()
if err != nil {
c.lgr.Errorf("[MIoTClient] Cert refresh: gen CSR FAILED: %v\n", err)
logrus.Errorf("[MIoTClient] Cert refresh: gen CSR FAILED: %v\n", err)
c.RequestRefreshUserCert(3600)
return
}
@@ -714,18 +708,18 @@ func (c *MIoTClient) refreshUserCert() {
// Request cert from cloud
certPEM, err := c.http.GetCentralCert(csr)
if err != nil {
c.lgr.Errorf("[MIoTClient] Cert refresh: get cert from cloud FAILED: %v\n", err)
logrus.Errorf("[MIoTClient] Cert refresh: get cert from cloud FAILED: %v\n", err)
c.RequestRefreshUserCert(RefreshCertRetryDelay)
return
}
// Save cert
if err = c.cert.SaveUserCert(certPEM); err != nil {
c.lgr.Errorf("[MIoTClient] Cert refresh: save cert FAILED: %v\n", err)
logrus.Errorf("[MIoTClient] Cert refresh: save cert FAILED: %v\n", err)
return
}
c.lgr.Infof("[MIoTClient] Cert refreshed successfully\n")
logrus.Infof("[MIoTClient] Cert refreshed successfully\n")
// Update MIPS local clients with new certs (if any are still connected)
for _, mips := range c.mipsLocal {
@@ -783,13 +777,13 @@ func (c *MIoTClient) ShowCentralStateChangedNotify(connected bool) {
// Aligns with Python: __on_mips_cloud_state_changed.
func (c *MIoTClient) onMipsCloudStateChanged(key string, connected bool) {
if connected {
c.lgr.Debugf("[MIoTClient] MIPS cloud connected\n")
logrus.Debugf("[MIoTClient] MIPS cloud connected\n")
// Refresh devices on reconnect
c.ScheduleRefreshDevices(RefreshCloudDevicesDelay * time.Millisecond)
return
}
c.lgr.Debugf("[MIoTClient] MIPS cloud disconnected\n")
logrus.Debugf("[MIoTClient] MIPS cloud disconnected\n")
// Disconnect: mark all cloud devices offline
c.deviceListMu.Lock()
@@ -821,7 +815,7 @@ func (c *MIoTClient) onMipsCloudStateChanged(key string, connected bool) {
// onNetworkStatusChanged handles network connectivity changes.
// Aligns with Python: __on_network_status_changed.
func (c *MIoTClient) onNetworkStatusChanged(status bool) {
c.lgr.Debugf("[MIoTClient] Network status changed: online=%v\n", status)
logrus.Debugf("[MIoTClient] Network status changed: online=%v\n", status)
if status {
// Network is back; trigger device refresh and reconnect MIPS
if c.mipsCloud != nil && !c.mipsCloud.IsConnected() {
@@ -834,15 +828,15 @@ func (c *MIoTClient) onNetworkStatusChanged(status bool) {
// onMipsServiceStateChange handles mDNS service discoveries for central gateways.
// Aligns with Python: __on_mips_service_state_change.
func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceState, data map[string]interface{}) {
c.lgr.Debugf("[MIoTClient] MIPS service change: group=%s, state=%s\n", groupID, state)
logrus.Debugf("[MIoTClient] MIPS service change: group=%s, state=%s\n", groupID, state)
virtualDID := getVirtualDID(c.entryData)
if virtualDID == "" {
c.lgr.Debugf("[MIoTClient] MIPS service: missing virtual_did, skip\n")
logrus.Debugf("[MIoTClient] MIPS service: missing virtual_did, skip\n")
return
}
if c.cert == nil {
c.lgr.Debugf("[MIoTClient] MIPS service: cert not initialized, skip\n")
logrus.Debugf("[MIoTClient] MIPS service: cert not initialized, skip\n")
return
}
@@ -851,7 +845,7 @@ func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceS
// Create new MipsLocalClient
host, _ := data["addresses"].([]interface{})
if len(host) == 0 {
c.lgr.Debugf("[MIoTClient] MIPS service: no addresses for %s\n", groupID)
logrus.Debugf("[MIoTClient] MIPS service: no addresses for %s\n", groupID)
return
}
hostStr, _ := host[0].(string)
@@ -872,7 +866,7 @@ func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceS
mips.SubState(groupID, c.onMipsLocalStateChanged)
mips.Connect()
c.mipsLocal[groupID] = mips
c.lgr.Debugf("[MIoTClient] MIPS local client created: %s @ %s:%d\n", groupID, hostStr, int(port))
logrus.Debugf("[MIoTClient] MIPS local client created: %s @ %s:%d\n", groupID, hostStr, int(port))
case MipsServiceUpdated:
// Disconnect old, connect new
@@ -902,7 +896,7 @@ func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceS
mips.SubState(groupID, c.onMipsLocalStateChanged)
mips.Connect()
c.mipsLocal[groupID] = mips
c.lgr.Debugf("[MIoTClient] MIPS local client updated: %s @ %s:%d\n", groupID, hostStr, int(port))
logrus.Debugf("[MIoTClient] MIPS local client updated: %s @ %s:%d\n", groupID, hostStr, int(port))
case MipsServiceRemoved:
if mips, exists := c.mipsLocal[groupID]; exists {
@@ -910,7 +904,7 @@ func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceS
mips.UnsubState(groupID)
mips.Disconnect()
delete(c.mipsLocal, groupID)
c.lgr.Debugf("[MIoTClient] MIPS local client removed: %s\n", groupID)
logrus.Debugf("[MIoTClient] MIPS local client removed: %s\n", groupID)
}
}
}
@@ -919,7 +913,7 @@ func (c *MIoTClient) onMipsServiceStateChange(groupID string, state MipsServiceS
// Aligns with Python: __on_mips_local_state_changed.
// key is the groupID of the gateway.
func (c *MIoTClient) onMipsLocalStateChanged(key string, connected bool) {
c.lgr.Debugf("[MIoTClient] MIPS local state changed: group=%s, connected=%v\n", key, connected)
logrus.Debugf("[MIoTClient] MIPS local state changed: group=%s, connected=%v\n", key, connected)
if connected {
// Reconnect: pull gateway device list
@@ -966,7 +960,7 @@ func (c *MIoTClient) onMipsLocalStateChanged(key string, connected bool) {
// onMiotLanStateChange handles LAN controller state transitions.
// Aligns with Python: __on_miot_lan_state_change.
func (c *MIoTClient) onMiotLanStateChange(initialized bool) {
c.lgr.Debugf("[MIoTClient] LAN state changed: initialized=%v\n", initialized)
logrus.Debugf("[MIoTClient] LAN state changed: initialized=%v\n", initialized)
if initialized {
c.deviceListMu.Lock()
lan, ok := c.miotLan.(*MIoTLan)
@@ -1026,7 +1020,7 @@ func (c *MIoTClient) onLanDeviceStateChanged(did string, state map[string]interf
// Aligns with Python: __on_gw_device_list_changed.
// Called when a MipsLocalClient reports that its device list has changed.
func (c *MIoTClient) onGWDeviceListChanged() {
c.lgr.Debugf("[MIoTClient] GW device list changed\n")
logrus.Debugf("[MIoTClient] GW device list changed\n")
for groupID, mips := range c.mipsLocal {
if mips == nil || !mips.IsConnected() {
@@ -1036,7 +1030,7 @@ func (c *MIoTClient) onGWDeviceListChanged() {
// Pull device list from gateway
payload, err := mips.GetDevList("", MipsRequestTimeoutDefault*time.Millisecond)
if err != nil {
c.lgr.Errorf("[MIoTClient] GW device list pull failed for %s: %v\n", groupID, err)
logrus.Errorf("[MIoTClient] GW device list pull failed for %s: %v\n", groupID, err)
continue
}
@@ -1045,7 +1039,7 @@ func (c *MIoTClient) onGWDeviceListChanged() {
Result map[string]interface{} `json:"result"`
}
if err := json.Unmarshal([]byte(payload), &result); err != nil {
c.lgr.Errorf("[MIoTClient] GW device list parse failed for %s: %v\n", groupID, err)
logrus.Errorf("[MIoTClient] GW device list parse failed for %s: %v\n", groupID, err)
continue
}
@@ -1090,7 +1084,7 @@ func (c *MIoTClient) updateDevicesFromGW(groupID string, devices map[string]inte
}
if changed {
c.lgr.Debugf("[MIoTClient] GW devices updated: group=%s, count=%d\n", groupID, len(devices))
logrus.Debugf("[MIoTClient] GW devices updated: group=%s, count=%d\n", groupID, len(devices))
}
}