Should I use fmt.Println() or log.Println() in my CLI app in Go ?

· 336 words · 2 minute read

Choosing between fmt.Println() and log.Println() in your CLI application depends on your specific needs regarding output formatting, verbosity, and where the output goes (stdout vs stderr).

  • fmt.Println() is part of the standard library and is suitable for general-purpose output. It prints to stdout by default, which is typically where you’d want your CLI application’s output to go. It’s straightforward to use and doesn’t require any setup beyond importing the fmt package. However, it lacks the structured logging capabilities that log.Println() offers.

  • log.Println(), on the other hand, is specifically designed for logging purposes. It prefixes each output with a timestamp and the name of the package, providing structured logging that can be very helpful for debugging and monitoring applications. Like fmt.Println(), it prints to stdout by default, but you can configure it to print to stderr or another destination if needed. Using log.Println() makes it easier to control the verbosity of your application through different log levels (e.g., debug, info, warn, error).

If your CLI application requires simple output for user interaction or debugging purposes, fmt.Println() is sufficient. However, if you’re developing an application where logging is crucial for understanding the flow of execution, especially in production environments, log.Println() is the better choice due to its structured logging capabilities and flexibility.

Here’s a quick comparison:

  • Use fmt.Println() for:

    • Simple output to stdout.
    • No need for structured logging or controlling verbosity.
  • Use log.Println() for:

    • Structured logging with timestamps and package names.
    • Controlling output verbosity through log levels.
    • Printing to destinations other than stdout if configured.

So, use fmt.Println() as the go to way of printing text on terminal. And use log.Println(), if your application needs the additional features provided by log.Println().

I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , Facebook , Telegram and GitHub .

Share:
waffarx cash back