第一步 先出一个大体的思路
package main
import (
"fmt"
"strings"
"time"
)
//----------实现日志统计 存储到influxdb 实现展示---------------------
type LogStatistics struct {
Path string //日志的位置
Influxdb string //influxdb 的数据库名和数据库密码
Rc chan string //读取的chan 定义为string
Wc chan string //写入的chan 定义为string
}
//-----------使用者第一步读取日志----------------
func (l *LogStatistics) ReadLog() {
msg := "hello World"
l.Wc <- msg
}
//-----------使用者第二步写入日志----------------
func (l *LogStatistics) WriteLog() {
data := <-l.Wc
l.Rc <- data
}
//-----------使用者第三步解析日志----------------
func (l *LogStatistics) Analysis() {
fmt.Printf("%v", strings.ToUpper(<-l.Rc))
}
func main() {
log := &LogStatistics{Path: "nginx/log/nginx.log", Influxdb: "user@root", Rc: make(chan string), Wc: make(chan string)}
go log.ReadLog()
go log.WriteLog()
go log.Analysis()
time.Sleep(1 * time.Second)
}
第二步 优化一下代码
package main
import (
"fmt"
"strings"
"time"
)
//----------实现一个读取的接口和写入的接口,目的是为了实现多种方式的读取和写入
type ReadLog interface {
Read(rc chan string)
}
type WriteLog interface {
Write(wc chan string)
}
//----------实现日志统计 存储到influxdb 实现展示---------------------
type LogStatistics struct {
rc chan string //读取的chan 定义为string
wc chan string //写入的chan 定义为string
//------两个chan用来对数据进行传输,读取和写入------
w WriteLog //写入log
r ReadLog //读取log
//--------这两个参数用来实现读去和写入模块----------
}
//------------实现一个多种方式读取的结构体--------
type ReadLogs struct {
Path string //日志的位置
}
//------------实现一个多种方式写入的结构体--------
type WriteLogs struct {
Influxdb string //influxdb 的数据库名和数据库密码
}
//-----------使用者第一步读取日志----------------
func (r *ReadLogs) Read(rc chan string) {
msg := "hello World"
rc <- msg
}
//-----------使用者第二步写入日志----------------
func (w *WriteLogs) Write(wc chan string) {
fmt.Println(<-wc)
}
//-----------使用者第三步解析日志----------------
func (l *LogStatistics) Analysis() {
l.wc <- strings.ToUpper(<-l.rc)
}
func main() {
w := &WriteLogs{Influxdb: "user@root"}
r := &ReadLogs{Path: "log.log"}
// var w WriteLogs
//var r ReadLogs
logs := &LogStatistics{
rc: make(chan string),
wc: make(chan string),
w: w,
r: r,
}
go logs.r.Read(logs.rc)
go logs.w.Write(logs.wc)
go logs.Analysis()
time.Sleep(1 * time.Second)
}
网友评论