In this program, we will write log into the specified file using log.SetOutput() andlog.Print() function. Log message saved with a timestamp into the specified file.
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 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.
rogram/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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer