Golang program to write log into specified file using log.SetOutput() function

Here, we are going to learn how to write log into specified file using log.SetOutput() function in Golang (Go Language)?
Submitted by Nidhi, on April 22, 2021 [Last updated : March 05, 2023]

How to write log into specified file in Golang?

Problem Solution:

In this program, we will write log into the specified file using log.SetOutput() and log.Print() function. Log message saved with a timestamp into the specified file.

Program/Source Code:

The source code to write log into the specified file using log.SetOutput() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to write log into specified file using log.SetOutput() function

// Golang program to write log into specified
// file using log.SetOutput() 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)
	}

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

$ cat mylogs.log 
2021/04/22 01:46:18 Log line1
2021/04/22 01:46:18 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 used log.SetOutput() function to set output of log.Print() function into a file bind using log.SetOutput() function.

Golang log Package Programs »






Comments and Discussions!

Load comments ↻






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