How do I set log levels using standard log in Go?

In Go, the standard log package does not provide built-in support for log levels such as DEBUG, INFO, WARN, ERROR, etc. However, you can achieve a similar effect by creating a custom logging utility that wraps the standard log functions and uses a global log level to control what gets logged. Below is an example of how you can implement log levels in Go.

package main import ( "fmt" "log" "os" "strings" ) // Define the log levels const ( DEBUG = iota INFO WARN ERROR ) var currentLogLevel = INFO // Set the default log level func SetLogLevel(level int) { currentLogLevel = level } func Log(level int, message string) { if level >= currentLogLevel { log.Println(message) } } func main() { // Set log level to DEBUG SetLogLevel(DEBUG) // Log messages of different levels Log(DEBUG, "This is a DEBUG message.") Log(INFO, "This is an INFO message.") Log(WARN, "This is a WARNING message.") Log(ERROR, "This is an ERROR message.") }

Go log levels Go logging standard log Go example