在CentOS上配置Golang日志,你可以使用标准库"log"或者第三方日志库,如"logrus"或"zap"。下面是使用标准库"log"进行配置的方法:
import (
"log"
)
func main() {
log.Println("This is an info log.")
log.Printf("This is a formatted log with a number: %d", 42)
log.Println("This is an error log.")
}
touch myapp.log
func main() {
logFile, err := os.OpenFile("myapp.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening log file: %v", err)
}
defer logFile.Close()
log.SetOutput(logFile)
log.Println("This is an info log.")
log.Printf("This is a formatted log with a number: %d", 42)
log.Println("This is an error log.")
}
tail命令实时查看日志文件:tail -f myapp.log
例如,使用"logrus":
go get github.com/sirupsen/logrus
package main
import (
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
logrus.Info("This is an info log.")
logrus.WithFields(logrus.Fields{
"number": 42,
}).Info("This is a formatted log with a number.")
logrus.WithFields(logrus.Fields{
"error": "This is an error log.",
}).Error("This is an error log.")
}
tail命令查看。