Q:

Golang program to add program filename in log message as a prefix using log.SetFlags() function

belongs to collection: Golang log Package Programs

0

Here, we will use log.SetFlags() function to add program filename in log message as a prefix. Here, we will pass log.Lshortfile constant in log.SetFlags() function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to add program filename in log message as a prefix using log.SetFlags() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Golang program to add program filename
// as a prefix in the log message

package main

import "log"
import "fmt"

func main() {

	//program filename as a prefix
	log.SetFlags(log.Lshortfile)

	log.Println("Log Line1")
	log.Println("Log Line2")

	fmt.Println("Program finished")
}

Output:

$ go run hello.go 
hello.go:14: Log Line1
hello.go:15: Log Line2
Program finished

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 functions.

In the main() function, we added program filename as a prefix in every line of log message using log. Lshortfile constant in logSetFlags() function.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to set the standard flags for times... >>
<< Golang program to add the full path of program fil...