Q:

Golang program to demonstrate the log.SetPrefix() function

belongs to collection: Golang log Package Programs

0

In this program, we will set a string as a prefix in every line of the log file using SetPrefix() function. Here, we will write log into the file using log.SetOutput() and log.Print() 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 demonstrate the log.SetPrefix() 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.SetPrefix() function

package main

import "log"
import "os"
import "fmt"

func main() {
	filePtr, err := os.OpenFile("mylogs.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(err)
	}

	log.SetPrefix("#####-> ")
	//Set log output to the "mylogs.log" file.
	log.SetOutput(filePtr)

	log.Print("Log line1")
	log.Print("Log line2")

	filePtr.Close()

	fmt.Println("Program finished")
}

Output:

$ go run hello.go 
Program finished
arvind@ubuntu:~/Downloads$ cat mylogs.log 
#####-> 2021/04/20 01:54:38 Log line1
#####-> 2021/04/20 01:54:38 Log line2

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 open or create a file using os.OpenFile() function. Then we set the output of the log into the created file using log.SetOutput() function and set prefix string for every line of log file using log.SetPrefix() function. After that, we printed the "Program finished" message using fmt.Println() function on the console screen.

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

total answers (1)

Golang program to set date and time flags using lo... >>
<< Golang program to write log into specified file us...