Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 639
Rahul Prasad Avatar asked Mar 31 '14 10:03

Rahul Prasad


People also ask

How do I log into a file in Golang?

To log to a file, you can use the OS package to create a log file if it does not exist or open and write to an existing file. Doing so will set the output of the log package to the specified output file. Keep in mind that the log package also supports other output destination that supports io.

What does log do in Golang?

The package log in Golang implements the simple logging package. It defines a type, Logger, with methods for formatting output. Golang Log will be helpful in the critical scenarios in real-time applications.

What is log Fatalf in Golang?

In this program, we will use log. Fatal() function to print specified message with timestamp on the console screen. The log. Fatal() is similar to the log. Print() function followed by a call to os.


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 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.

like image 169
Linear Avatar answered Sep 28 '22 03:09

Linear


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

like image 37
Volker Avatar answered Sep 28 '22 01:09

Volker