×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to set date and time flags using log.SetFlags() for log messages

Here, we are going to learn how to set date and time flags using log.SetFlags() for log messages in Golang (Go Language)?
Submitted by Nidhi, on April 23, 2021 [Last updated : March 05, 2023]

How to set date and time flags in Golang?

Problem Solution:

Here, we will use a log.SetFlags() function with some constants of log package to set flags for log messages.

Program/Source Code:

The source code to set date and time flags using log.SetFlags() for log messages is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to set date and time flags using log.SetFlags() for log messages

// Golang program to set date and time flags
// using log.SetFlags() for log messages

package main

import "log"
import "fmt"

func main() {
	log.SetFlags(log.Ldate)
	log.Println("Log line1")

	log.SetFlags(log.Ltime)
	log.Println("Log line2")

	log.SetFlags(log.Lmicroseconds)
	log.Println("Log line3")

	log.SetFlags(log.Ltime | log.LUTC)
	log.Println("Log line4")

	fmt.Println("Program finished")
}

Output:

2021/04/23 Log line1
16:30:22 Log line2
16:30:22.342067 Log line3
16:30:22 Log line4
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 set date and time flags using log.SetFlags() function. The log.SetFlags() function is used to set some prefix value to the log messages.

Golang log Package Programs »





Comments and Discussions!

Load comments ↻





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