In Go, log levels are not built-in, but you can define your own log levels and use them to control the verbosity of log output. Here's a step-by-step guide on how to accomplish this:
type
to represent the different log levels. You can use the int
type with iota to assign integer values to each log level. For example:type LogLevel int
const (
Debug LogLevel = iota
Info
Warning
Error
)
log
package's New()
method to create a logger instance. This will allow you to specify the output destination, such as standard output or a file. For example:logger := log.New(os.Stdout, "", log.LstdFlags)
func isLogLevelEnabled(currentLevel, logLevel LogLevel) bool {
return logLevel >= currentLevel
}
isLogLevelEnabled()
function. If the log level is enabled, output the log message using the logger. For example:func LogMessage(currentLevel, logLevel LogLevel, message string) {
if isLogLevelEnabled(currentLevel, logLevel) {
logger.Println(message)
}
}
currentLevel := Info // Set log level to 'Info'
LogMessage(currentLevel, Debug, "This is a debug message")
LogMessage(currentLevel, Info, "This is an info message")
LogMessage(currentLevel, Warning, "This is a warning message")
LogMessage(currentLevel, Error, "This is an error message")
By using log levels to control the verbosity of log output, you can easily adjust the amount of information that is logged based on your needs.