Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use log.Println instead of fmt.Println?

Tags:

logging

go

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 for fmt.Sprintln , why should I use it instead of fmt.Println or fmt.Sprintln ?

Any practical reasons ?

like image 818
Salah Eddine Taouririt Avatar asked Oct 28 '13 23:10

Salah Eddine Taouririt


People also ask

What is FMT Println?

The fmt. Println() function in Go language formats using the default formats for its operands and writes to standard output. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package.

What is the difference between Println and printf in Golang?

Here Printf formats according to a specified format specifier but Println uses the default formats for its operands.

What is FMT printf?

The fmt. out. printf() function in Golang allows users to print formatted data. The function takes a template string that contains the text that needs to be formatted, plus some annotation verbs that tell the fmt functions how to format the trailing arguments.

What is Println go?

We use Println() to write the input data stream to the standard output. It is a variadic function, which means that it takes a variable number of input arguments. The functionality of Println() in Golang is similar to print in python or printf in C.


1 Answers

Two things are different:

  1. Printing via package log is safe from concurrent goroutines (while plain fmt isn't)

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

like image 162
Volker Avatar answered Sep 21 '22 13:09

Volker