Golang: writes to a file using log.Println takes care of concurrent access

I have hundreds of routines writing to a log file using log.Println ()
I use log.Println to write to the 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 right? Or should I use the channel to make sure that only one process registers to the file at a time or takes care of it in its own way by the log folder?

Also does the log package take care of buffering or write directly to a file?

+7
logging file-io go buffer
source share
2 answers

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 almost all functions of the output of the log package pass through Output , and there is a mutex in Output , we can say that they are concurrency -safe.

+14
source share

I can really recommend reading the documentation:

A logger is an active logging object that generates output lines to the io.Writer file. Each registration operation makes one call to the Writer recording method. The logger can be used simultaneously from several goroutines; it guarantees serialization of access to Writer.

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

+16
source share

All Articles