在Golang中,可以使用标准库"log"或第三方库(如"logrus"或"zap")来自定义日志格式。下面是使用标准库"log"自定义日志格式的方法:
import (
"log"
"os"
)
type customLogger struct {
logger *log.Logger
}
func (cl *customLogger) log(prefix string, flag int, msg string) {
// 自定义日志格式
formattedMsg := fmt.Sprintf(prefix+msg+"\n", cl.logger.Flags())
// 输出日志
fmt.Print(formattedMsg)
}
func customOutput(prefix string, flag int, msg string) {
cl.log(prefix, flag, msg)
}
func newCustomLogger(prefix string, flag int) *customLogger {
return &customLogger{
logger: log.New(os.Stdout, prefix, flag),
}
}
func main() {
cl := newCustomLogger("INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
cl.log("This is a custom log message", 0, "Hello, World!")
}
这将输出如下格式的日志:
INFO: 2022/01/01 12:00:00 main.go:25: Hello, World!
如果你想要使用第三方库来自定义日志格式,可以参考以下示例:
go get github.com/sirupsen/logrus
import (
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
filename := filepath.Base(f.File)
return filename, ""
},
})
logrus.Info("This is a custom log message")
}
这将输出如下格式的日志:
time="2022-01-01T12:00:00Z" level=info msg="This is a custom log message" file="main.go" line=25
你可以根据自己的需求调整日志格式。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: linux中find命令能按大小吗