作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有数百个子例程使用 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/
我是一名优秀的程序员,十分优秀!