在Linux环境下,Golang日志存储方案有很多种,以下是一些建议:
log.SetOutput()函数设置日志输出的目标文件。package main
import (
"log"
"os"
)
func main() {
logFile, err := os.OpenFile("logs/app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
defer logFile.Close()
log.SetOutput(logFile)
log.Println("This is a log message")
}
package main
import (
"go.uber.org/zap"
)
func main() {
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("This is an info message")
}
package main
import (
"github.com/sirupsen/logrus"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.Info("This is an info message")
}
lumberjack库来实现日志轮转。package main
import (
"gopkg.in/natefinch/lumberjack.v2"
"log"
)
func main() {
log.SetOutput(&lumberjack.Logger{
Filename: "logs/app.log",
MaxSize: 10, // 单个日志文件最大尺寸(MB)
MaxBackups: 3, // 最大备份数量
MaxAge: 28, // 日志文件最大保留天数
Compress: true, // 是否压缩旧日志文件
})
log.Println("This is a log message")
}
logstash-go库将日志发送到Logstash。package main
import (
"github.com/Shopify/sarama"
"github.com/tidwall/gjson"
"log"
"os"
"time"
)
func main() {
config := sarama.NewConfig()
config.Producer.RequiredAcks = sarama.WaitForAll
config.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer([]string{"localhost:9092"}, config)
if err != nil {
log.Fatal(err)
}
defer producer.Close()
topic := "logs"
partition := int32(0)
for {
logMessage := "This is a log message"
msg := &sarama.ProducerMessage{
Topic: topic,
Partition: partition,
Value: sarama.ByteEncoder(logMessage),
}
partition, offset, err := producer.SendMessage(msg)
if err != nil {
log.Fatal(err)
}
log.Printf("Message sent to partition %d at offset %d\n", partition, offset)
time.Sleep(1 * time.Second)
}
}
根据你的需求和场景,可以选择合适的日志存储方案。