Skip to content

fix: protect Logger.config with sync.RWMutex to prevent data race (#4795) - #4811

Open
waterWang wants to merge 4 commits into
gogf:masterfrom
waterWang:fix-glog-race
Open

fix: protect Logger.config with sync.RWMutex to prevent data race (#4795)#4811
waterWang wants to merge 4 commits into
gogf:masterfrom
waterWang:fix-glog-race

Conversation

@waterWang

Copy link
Copy Markdown
Contributor

Fix #4795os/glog: Logger.SetConfig 与并发日志输出(Info/Print 等)存在未加锁数据竞争(-race 确认)

Root Cause

Logger 结构体的 config Config 字段是裸字段,没有 sync.Mutex/sync.RWMutex/atomic 保护。
SetConfig 直接 l.config = config 无锁整体赋值,而包内几乎所有对外 API(Info/Print/checkLevel/SetLevel/SetPrefix 等)都不经过任何同步直接读写这个字段。

Fix

Logger 结构体中添加 sync.RWMutex,保护所有对 config 字段的并发访问:

  • 写操作SetConfig, SetConfigWithMap, SetLevel, SetLevelStr, SetLevelPrefix, SetLevelPrefixes, SetDebug, SetAsync, SetFlags, SetStack, SetStackSkip, SetStackFilter, SetCtxKeys, AppendCtxKeys, SetWriter, SetPath, SetFile, SetTimeFormat, SetStdoutPrint, SetHeaderPrint, SetLevelPrint, SetPrefix, SetHandlers, SetWriterColorEnable, SetStdoutColorDisabled):使用 Lock/Unlock
  • 读操作GetConfig, GetFlags, GetCtxKeys, GetWriter, GetPath, GetLevel, GetLevelPrefix, getLevelPrefixWithBrackets, checkLevel, GetStack):使用 RLock/RUnlock
  • 热路径print, doFinalPrint, printErr):使用 RLock/RUnlock,确保日志输出与配置变更并发安全

Changes

File Changes
os/glog/glog_logger.go 添加 mu sync.RWMutex 到 Logger struct;Clone()print()doFinalPrint()printErr()GetStack() 加锁
os/glog/glog_logger_config.go 所有 Set* 方法加 Lock;所有 Get* 方法加 RLock
os/glog/glog_logger_level.go SetLevel/GetLevel/SetLevelStr/SetLevelPrefix/SetLevelPrefixes/GetLevelPrefix/getLevelPrefixWithBrackets 加锁
os/glog/glog_logger_api.go checkLevel() 加 RLock

Verification

Bug reporter 提供的最小复现程序(go run -race)不应再触发 DATA RACE 警告。所有现有测试应继续通过。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

os/glog: Logger.SetConfig 与并发日志输出(Info/Print 等)存在未加锁数据竞争(-race 确认)

1 participant