gpt4 book ai didi

logging - Golang : Does logging into file using log. Println 负责并发访问

转载 作者:IT王子 更新时间:2023-10-29 01:06:29 25 4
gpt4 key购买 nike

我有数百个子例程使用 log.Println() 写入日志文件
我正在使用 log.Println 写入 error.log 文件。

func main() {
e, err := os.OpenFile("error.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("error opening file: %v", err)
os.Exit(1)
}
defer e.Close()
errLog := log.New(e, ">>>", log.Ldate|log.Ltime)

for i:=0; i<500; i++ {
go worker(errLog)
}
}

func worker(errLog log.Logger) {
// Do some work
errLog.Println("Hello world!!!")
}

我的方法正确吗?或者我应该使用 channel 来确保一次只有一个进程登录文件,还是由日志包固有地处理?

还有日志包是负责缓冲还是直接写入文件?

最佳答案

来自 log.go :

func (l *Logger) Output(calldepth int, s string) error {
now := time.Now() // get this early.
var file string
var line int
l.mu.Lock()
defer l.mu.Unlock()
// ... Rest omitted

因为几乎所有包 log 输出函数都经过 Output,并且 Output 中有一个互斥体,所以可以肯定地说它们是并发的-安全。

关于logging - Golang : Does logging into file using log. Println 负责并发访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com