在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日志格式了。你可以根據自己的需求修改格式化器的實現。