在Debian上自定义Golang日志格式,你可以使用标准库"log"或者第三方库(如"logrus"或"zap")来实现。下面是使用标准库"log"和"logrus"库的示例。
使用标准库"log"
package main
import (
"log"
"os"
"time"
)
type customFormatter struct{}
func (f *customFormatter) Format(entry *log.Entry) string {
return time.Now().Format(time.RFC3339) + " " + entry.Level.String() + ": " + entry.Message + "\n"
}
func main() {
log.SetFormatter(&customFormatter{})
log.SetOutput(os.Stdout)
log.Println("Hello, World!")
}
go build main.go
./main
使用"logrus"库
go get github.com/sirupsen/logrus
package main
import (
"github.com/sirupsen/logrus"
)
type customFormatter struct{}
func (f *customFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return []byte(time.Now().Format(time.RFC3339) + " " + entry.Level.String() + ": " + entry.Message + "\n"), nil
}
func main() {
logrus.SetFormatter(&customFormatter{})
logrus.SetOutput(os.Stdout)
logrus.Info("Hello, World!")
}
go build main.go
./main
这样,你就可以在Debian上自定义Golang日志格式了。你可以根据自己的需求修改格式化器的实现。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>