In this program, we will use a log.Fatalf() function to print formatted messages with timestamp on the console screen. The log.Fatalf() is similar to thelog.Printf() function followed by a call to os.Exit(1) function.
The source code to demonstrate the log.Fatalf() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Golang program to demonstrate the
// log.Fatalf() function
package main
// Import log package to use
// Fatalf() function to print log
import "log"
// Import fmt package to use Println() function
// to print the message on the console screen
import "fmt"
func main() {
var err int = 10
log.Fatalf("Error: %d", err)
fmt.Println("Program finished")
}
Output:
2021/04/22 13:51:19 Error: 10
Program exited: status 1.
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the "fmt" package to use the Println() function and we also imported the "log" package to use the log.Fatalf() function.
In the main() function, we used log.Fatalf() function to print formatted messages with timestamp on the console screen. Here, we printed the error number on the console screen.
The log.Fatalf() is similar to the log.Printf() function followed by a call to os.Exit(1) function.
The log.Fatalf() calls os.Exit(1) that's why, in above program fmt.Println() function did not call after log.Fatalf() function.
Program/Source Code:
The source code to demonstrate the log.Fatalf() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the "fmt" package to use the Println() function and we also imported the "log" package to use the log.Fatalf() function.
In the main() function, we used log.Fatalf() function to print formatted messages with timestamp on the console screen. Here, we printed the error number on the console screen.
The log.Fatalf() is similar to the log.Printf() function followed by a call to os.Exit(1) function.
The log.Fatalf() calls os.Exit(1) that's why, in above program fmt.Println() function did not call after log.Fatalf() function.
need an explanation for this answer? contact us directly to get an explanation for this answer