在 Ubuntu 上使用 Golang 编写应用程序时,可以通过以下几种方法设置日志级别:
在 Golang 的标准库中,可以使用 log 包来实现日志记录。但是,log 包本身不支持日志级别。为了实现日志级别,可以自定义一个简单的日志记录器。例如:
package main
import (
"log"
"os"
)
type LogLevel int
const (
DEBUG LogLevel = iota
INFO
WARNING
ERROR
)
var logger *log.Logger
func init() {
logger = log.New(os.Stdout, "", log.LstdFlags)
}
func setLogLevel(level LogLevel) {
logger.SetPrefix(getLogLevelString(level) + ": ")
}
func getLogLevelString(level LogLevel) string {
switch level {
case DEBUG:
return "DEBUG"
case INFO:
return "INFO"
case WARNING:
return "WARNING"
case ERROR:
return "ERROR"
default:
return "UNKNOWN"
}
}
func debug(msg string) {
if currentLogLevel <= DEBUG {
logger.Output(2, msg)
}
}
func info(msg string) {
if currentLogLevel <= INFO {
logger.Output(2, msg)
}
}
func warning(msg string) {
if currentLogLevel <= WARNING {
logger.Output(2, msg)
}
}
func error(msg string) {
if currentLogLevel <= ERROR {
logger.Output(2, msg)
}
}
func main() {
setLogLevel(INFO)
debug("This is a debug message")
info("This is an info message")
warning("This is a warning message")
error("This is an error message")
}
在这个例子中,我们定义了一个名为 LogLevel 的类型,以及四个常量:DEBUG、INFO、WARNING 和 ERROR。我们还定义了一个名为 setLogLevel 的函数,用于设置日志级别。根据设置的日志级别,可以控制日志的输出。
有许多第三方日志库支持日志级别,例如 logrus、zap 等。这些库提供了更丰富的功能和更好的性能。以下是使用 logrus 库的一个简单示例:
首先,安装 logrus:
go get github.com/sirupsen/logrus
然后,在代码中使用 logrus:
package main
import (
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetLevel(logrus.InfoLevel)
logrus.Debug("This is a debug message")
logrus.Info("This is an info message")
logrus.Warn("This is a warning message")
logrus.Error("This is an error message")
}
在这个例子中,我们使用 logrus 库设置了日志级别为 INFO。因此,只有 INFO、WARN 和 ERROR 级别的日志会被输出。