In Go, you can use the standard log
package to log messages. However, by default, it doesn't support custom log levels and priorities. If you need custom log levels, you can create a custom logger by wrapping the standard logger in a struct and defining your own log levels.
Here's an example implementation of a custom logger with custom log levels and priorities in Go:
package main
import (
"log"
"os"
)
type LogLevel int
const (
InfoLevel LogLevel = iota // 0
DebugLevel // 1
ErrorLevel // 2
)
type Logger struct {
*log.Logger
level LogLevel
}
func NewLogger(level LogLevel) *Logger {
return &Logger{
Logger: log.New(os.Stdout, "", log.LstdFlags),
level: level,
}
}
func (l *Logger) Info(v ...interface{}) {
if l.level <= InfoLevel {
l.Print("[INFO] ", v)
}
}
func (l *Logger) Debug(v ...interface{}) {
if l.level <= DebugLevel {
l.Print("[DEBUG] ", v)
}
}
func (l *Logger) Error(v ...interface{}) {
if l.level <= ErrorLevel {
l.Print("[ERROR] ", v)
}
}
func main() {
logger := NewLogger(DebugLevel)
logger.Info("This is an info message")
logger.Debug("This is a debug message")
logger.Error("This is an error message")
}
In this example, we define a custom LogLevel
type which represents the available log levels. We also define a Logger
struct that wraps the standard log.Logger
and has an additional level
field to define the current log level.
The NewLogger
function creates a new instance of the custom logger with the provided log level. The Info
, Debug
, and Error
methods are defined on the Logger
struct and check if the log level is enabled before logging the message.
In the main
function, we create a new logger with the log level set to DebugLevel
. Then we use the logger's Info
, Debug
, and Error
methods to log messages, and only the messages with a log level equal to or higher than the current log level will be printed.