Frage

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

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!!!")
}

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top