Golang:使用log.Println将日志记录到文件中,是否会处理并发访问?

huangapple go评论96阅读模式
英文:

Golang: Does logging into file using log.Println takes care of concurrent access

问题

我有数百个子程序使用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!!!")
}

我的方法正确吗?或者我应该使用通道来确保一次只有一个进程记录到文件中,或者日志包本身已经处理了这个问题?

另外,日志包是否会进行缓冲,还是直接写入文件?

英文:

I have hundreds of subroutines writing into log file using log.Println() <br>
I am using log.Println to write into error.log file. <br>

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

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

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

Is my approach correct ? Or should I use channel to make sure only one process is logging into file at one time or is it taken care of inherently by log package?

Also does log package takes care of buffering or it directly writes into file?

答案1

得分: 23

log.go 文件中:

func (l *Logger) Output(calldepth int, s string) error {
   now := time.Now() // 提前获取当前时间。
   var file string
   var line int
   l.mu.Lock()
   defer l.mu.Unlock()
   // ... 其余部分省略

由于几乎所有的 log 包输出函数都经过 Output 函数,并且 Output 函数中有一个互斥锁,可以说它们是并发安全的。

英文:

From 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

Since pretty much all package log output functions go through Output, and there's a mutex in Output it's safe to say they're concurrency-safe.

答案2

得分: 19

我真的可以推荐阅读文档:

> Logger代表一个活动的日志对象,它会生成输出行到一个io.Writer。每个日志操作都会调用Writer的Write方法一次。一个Logger可以同时从多个goroutine中使用;它保证对Writer的访问进行序列化。

请参阅http://golang.org/pkg/log/#Logger

英文:

I really can recommend reading the documentation:

> A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

See http://golang.org/pkg/log/#Logger

huangapple
  • 本文由 发表于 2014年3月31日 18:11:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/22758911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定