Golang program to demonstrate the log.SetPrefix() function

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

log.SetPrefix() function in Golang

Problem Solution:

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.

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 code to demonstrate the example of log.SetPrefix() function

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

Golang log Package Programs »






Comments and Discussions!

Load comments ↻






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