Why should I use log.Println instead of fmt.Println?
24,904
Two things are different:
Printing via package log is safe from concurrent goroutines (while plain
fmt
isn't)Log can add timing information automatically.
So these are two completely different things. log is for logging and fmt
for formatting. (Okay, log uses the same verbs and flags, but that is just convenient).
Author by
Salah Eddine Taouririt
Updated on July 08, 2022Comments
-
Salah Eddine Taouririt almost 2 years
From log.go (the implementation of the log package) :
167 // Println calls l.Output to print to the logger. 168 // Arguments are handled in the manner of fmt.Println. 169 func (l *Logger) Println(v ...interface{}) { l.Output(2, fmt.Sprintln(v...)) }
log.Println
is just a function wrapper forfmt.Sprintln
, why should I use it instead offmt.Println
orfmt.Sprintln
?Any practical reasons ?
-
Naor Shlomi over 8 yearsI like Log because of the timestamp. The downside to using Log is that it always writes to stderr.
-
Dave C over 8 years@rem7 it logs to
os.Stderr
by default. Simply calllog.SetOutput
to send it to anyio.Writer
(which might even be abytes.Buffer
). -
bsbak about 7 yearsPlease, can you add code example for
log is safe from concurrent goroutines
-
z11i over 4 yearsFor discussions around the safety of
log
andfmt
in goroutines, see stackoverflow.com/questions/14694088/…