Golang program to demonstrate the log.Panicf() function

Here, we are going to demonstrate the log.Panicf() function in Golang (Go Language).
Submitted by Nidhi, on April 22, 2021 [Last updated : March 05, 2023]

log.Panicf() function in Golang

Problem Solution:

In this program, we will use log.Panicf() function to print formatted message with timestamp on the console screen. The log.Panicf() is similar to the log.Printf() function followed by a call to Panic() function.

Program/Source Code:

The source code to demonstrate the log.Panicf() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to demonstrate the example of log.Panicf() function

// Golang program to demonstrate the
// log.Panicf() function

package main

// Import log package to use
// Panicf() function
import "log"

// Import fmt package to use Println() function
// to print the message on the console screen
import "fmt"

func main() {
	var err int = 32
	log.Panicf("Error number %d", err)
	fmt.Println("Program finished")
}

Output:

2021/04/20 01:03:41 Error number 32
panic: Error number 32

goroutine 1 [running]:
log.Panicf(0x4c78d3, 0xf, 0xc0000a2f58, 0x1, 0x1)
	/usr/local/go-faketime/src/log/log.go:361 +0xc5
main.main()
	/tmp/sandbox010096975/prog.go:16 +0x85

Program exited: status 2.

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.Panicf() function.

In the main() function, we used log.Panicf() function to print formatted messages with timestamp on the console screen. Here, we printed the error number on the console screen.

The log.Panicf() is similar to the log.Printf() function followed by a call to Panic() function.

The log.Panicf() function calls Panic() function that's why, in above program fmt.Println() function did not call after log.Panicf() function.

Golang log Package Programs »





All Golang Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.