tail模块
下载
go get github.com/hpcloud/tail
使用
package main
import (
"fmt"
"os"
"time"
"github.com/hpcloud/tail"
)
/*
type Config struct {
// File-specifc
Location *SeekInfo // 在seek的位置开始读
ReOpen bool // 重新打开重新创建的文件 (tail -F)
MustExist bool // 如果文件不存在,则会提前失败,false则不会报错
Poll bool // 轮询文件更改而不是使用 inotify
Pipe bool // 命名管道 (mkfifo)
RateLimiter *ratelimiter.LeakyBucket
// Generic IO
Follow bool // 继续寻找新行 (tail -f)
MaxLineSize int // 如果非零,则将较长的行拆分为多行
// Logger,当 nil 时,设置为 tail.DefaultLogger
// 要禁用日志记录:将字段设置为 tail.DiscardingLogger
Logger logger
}
*/
func checkErr(err error) {
if err != nil {
fmt.Println("ERROR:", err)
os.Exit(1)
}
}
//go get github.com/hpcloud/tail
func main() {
fileName := "./test.log"
config := tail.Config{
ReOpen: true, // 重新打开
Follow: true, // 是否跟随
Location: &tail.SeekInfo{Offset: 0, Whence: 2}, // 从文件的哪个地方开始读
MustExist: false, // 文件不存在不报错
Poll: true,
}
tails, err := tail.TailFile(fileName, config)
if err != nil {
fmt.Println("tail file failed, err:", err)
return
}
var (
line *tail.Line
ok bool
)
for {
line, ok = <-tails.Lines //遍历chan,读取日志内容
if !ok {
fmt.Printf("tail file close reopen, filename:%s\n", tails.Filename)
time.Sleep(time.Second)
continue
}
fmt.Println("line:", line.Text)
}
}
运行程序,用记事本打开test.log文件并写入内容进行保存,下面显示结果:
2022/03/28 22:06:34 Seeked ./test.log - &{Offset:0 Whence:2}
line: hello
line: world
sarama模块
下载
go get github.com/Shopify/sarama
使用
package main
import (
"bufio"
"fmt"
"os"
"github.com/Shopify/sarama"
)
//go get github.com/Shopify/sarama
//基于sarama第三方库开发kafka客户端
func main() {
config := sarama.NewConfig()
//NoResponse 不发送任何响应
//WaitForLocal 只在响应之前等待本地提交成功
//WaitForAll 响应之前等待所有同步副本提交
config.Producer.RequiredAcks = sarama.WaitForAll //发送完数据需要leader和follow都确认
config.Producer.Return.Successes = true //成功传递的消息将在成功通道上返回。
config.Producer.Partitioner = sarama.NewRandomPartitioner //新选出一个分区
//创建一个生产者,连接kafka
client, err := sarama.NewSyncProducer([]string{"192.168.1.5:9092"}, config)
if err != nil {
panic(err)
}
defer client.Close()
for {
fmt.Print("->")
reader := bufio.NewReader(os.Stdin)
buf, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
message := &sarama.ProducerMessage{Topic: "my_topic", Value: sarama.StringEncoder(buf)}
_, _, err = client.SendMessage(message)
if err != nil {
panic(err)
}
}
}