3

When writing to stdout or a log, how can I make sure that the output from several goroutines aren't messing up the output?

e.g. make sure the output will be like this

Routine 1 found 1235 entries
Routine 3 found 999 entries
Routine 2 found 24 entries

and NOT like this

Routine 1 fouRoutine 3 found 999 entries
nd 1235 entriRoutine 2 found 24 entries
es

I mean the output from one goroutine is not writing at the same time as another

i.e. is there a library or a standard way to get a semaphore around the output?

George Netu
  • 2,758
  • 4
  • 28
  • 49
Susan D. Taylor
  • 669
  • 2
  • 7
  • 17

1 Answers1

6

Use the log package for logging. From log.Logger:

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.

The fmt package is generally not safe to use with more than one goroutine.

If time (synchronizing of lock) is of concern, prepend the log statement with go:

go log.Println("some log")

Note however, that the log output then may be (most certainly) delayed.

Community
  • 1
  • 1
nemo
  • 55,207
  • 13
  • 135
  • 135
  • thank you for the quick answer; a question _"If time (synchronizing of lock) is of concern"_ what do you mean with that? when for example would it matter to prepend with go? (since the log package by itself seems to guarantee that it only writes one at a time...) – Susan D. Taylor Dec 11 '13 at 12:27
  • 1
    @SusanD.Taylor When using the standard logging of the `log` package there is a lock which prevents more than one goroutine from writing to the log. This means that all other goroutines have to wait when logging. This can be a bottle neck when you are logging excessively but can be avaoided by running the logging in a new goroutine. This on the other hand leads to the log messages being asynchronous and detached from the goroutine's actual flow. – nemo Dec 11 '13 at 15:30
  • ah ok, got it! Thank you for taking the time and explain! – Susan D. Taylor Dec 11 '13 at 16:40