log. Sprintf

65 views
Skip to first unread message

David Renne

unread,
Oct 18, 2017, 3:18:10 PM10/18/17
to golang-nuts
I had a question that I cant seem to figure out.  I know fmt is a bad package to use if you have any concurrent workers because it uses f.Write() and is not thread safe apparently.

But I like using Sprintf because I can format strings and return as a string.  How can I implement something to use the log package in a manner that I can have a concurrently safe log function which acts like Sprintf()?

It's just so strange to me and I have always been curious of why there isnt a log.Sprintf().

Alex Buchanan

unread,
Oct 18, 2017, 3:48:49 PM10/18/17
to golang-nuts
You mean fmt.Fprintf right? Formatting a string without writing to a io.Writer (fmt.Sprintf) must be safe for concurrent use.

The "log" package should be safe for concurrent use, and has a Printf function:

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

Rob Pike

unread,
Oct 18, 2017, 4:20:00 PM10/18/17
to Alex Buchanan, golang-nuts
fmt.Fprintf is fine for concurrent use if you use it properly. It does a single write system call to the output once the result is created. C does not guarantee that, if that's how you came to think it unsafe.

The same applies to log.Printf.

-rob


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages