Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use log over fmt for debugging and printing error?

Tags:

go

I know that we can print variable or error using log and fmt. for example if I want to print variable I can do this :

h := "world"
fmt.Printf("hello = %v\n", h)
log.Printf("halo = %v\n", h)

the output would be :

hello = world
2016/12/30 09:13:12 halo = world

and usually in the error handling I found log like this

if err != nil {
    log.Println("Error : something terrible happen -> ", err)
    return err
}

but from above case I could also use fmt to print the error like this

fmt.Printf("Error : something terrible happen -> %v\n",err.Error())

Is it a good practice to use fmt instead of log for printing the error? And then I always use fmt instead of log for printing the variable when debugging.

like image 733
Gujarat Santana Avatar asked Dec 30 '16 02:12

Gujarat Santana


4 Answers

Select between log and fmt using these facts:

  • The log functions print to stderr by default and can directed to an arbitrary writer. The fmt.Printf function prints to stdout.
  • The log functions can print timestamp, source code location and other info.
  • The log functions and fmt.Printf are both thread safe, but concurrent writes by fmt.Printf above an OS dependent size can be interleaved.

The answer to the three sub questions are "it depends".

like image 178
Bayta Darell Avatar answered Sep 18 '22 14:09

Bayta Darell


I would like to add one more point:

  • Log is thread safe where as fmt is not.

    A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

Link

like image 31
James Avatar answered Sep 21 '22 14:09

James


You generally don't get into trouble if you stick to use fmt.Print* for program output and log.* for program logging.

Of course if your program doesn't have "local" output (as most network server programs) you could use both for logging, but for logging log.* is more flexible and apt.

like image 42
Pablo Lalloni Avatar answered Sep 18 '22 14:09

Pablo Lalloni


From "Essential Go" book

Standard package log offers more functionality:

log.Printf("Logging")
log.Printf("Second line\n")

2019/03/26 10:07:11 Logging
2019/03/26 10:07:11 Second line

Compared to fmt.Printf, log.Printf:

  • By default logs to stderr (os.Stderr)
  • Adds current time to each log line
  • Ensures that echo log is on it’s own line by adding \n if not explicitly provided

To log fatal issues:

f, err := os.Open("file.txt")
if err != nil {
    log.Fatalf("os.Open('file.txt') failed with '%s'\n", err)
}

log.Fatalf logs the message and calls os.Exit(1) to end the process.

like image 40
Vlad Bezden Avatar answered Sep 19 '22 14:09

Vlad Bezden