Golang program to set the standard flags for timestamp as a prefix in the log message

Here, we are going to learn how to set the standard flags for timestamp as a prefix in the log message in Golang (Go Language)?
Submitted by Nidhi, on April 23, 2021 [Last updated : March 05, 2023]

How to set the standard flags for timestamp as a prefix in the log message in Golang?

Problem Solution:

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

By default standard flags are used, but if we set some other flags then we need to use the log.LstdFlags constant to set the default standard flag.

Program/Source Code:

The source code to set standard flags for timestamp as a prefix in the log message is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to set the standard flags for timestamp as a prefix in the log message

// Golang program to set standard flags
// 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")

	//Set standard flags.
	log.SetFlags(log.LstdFlags)
	log.Println("Log Line2")

	fmt.Println("Program finished")
}

Output:

main.go:12: Log Line1
2021/04/23 17:21:57 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. After that, we added timestamp as a prefix in every line of log message using log. LstdFlags constant in logSetFlags() function.

Golang log Package Programs »





All Golang Programs

Comments and Discussions!

Load comments ↻





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