1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
| package main
import ( "strings" "fmt" "time" "os" "bufio" "io" "regexp" "log" "strconv" "net/url"
"github.com/influxdata/influxdb/client/v2" "flag" "net/http" "encoding/json" )
// 定义两个接口,抽象读取模块和写入模块 type Reader interface { Read(rc chan []byte) }
type ReadFromFile struct { path string // 读取文件的路径 }
func (l *ReadFromFile) Read(rc chan []byte) { // 读取模块
// 1. 打开文件 f,err := os.Open(l.path) if err != nil { panic(fmt.Sprintf("open file error : %s \n", err)) }
// 2. 从文件末尾开始逐行读取文件内容 f.Seek(0,2) rd := bufio.NewReader(f)
// 3. 写入到Read Channel中 for { line, err := rd.ReadBytes('\n') if err == io.EOF { time.Sleep(500 * time.Millisecond) continue } else if err != nil { panic(fmt.Sprintf("ReadBytes error : %s", err.Error())) } TypeMonitorChan <- TypeHandleLine rc <- line[:len(line) - 1] } }
type Writer interface { Write(wc chan *Message) }
type WriteToInfluxDB struct { influxDBDsn string // influx data source }
func (l *WriteToInfluxDB) Write(wc chan *Message) { // 写入模块 // 1.初始化influxDB client // 2.从Write Channel中读取监控数据 // 3.构造数据并写入influxDB
infSli := strings.Split(l.influxDBDsn, "@")
// Create a new HTTPClient c, err := client.NewHTTPClient(client.HTTPConfig{ Addr: infSli[0], Username: infSli[1], Password: infSli[2], }) if err != nil { log.Fatal(err) }
for v := range wc{ fmt.Println(v) defer c.Close()
// Create a new point batch bp, err := client.NewBatchPoints(client.BatchPointsConfig{ Database: infSli[3], Precision: infSli[4], }) if err != nil { log.Fatal(err) }
// Create a point and add to batch tags := map[string]string{"Path": v.Path, "Method": v.Method, "Scheme": v.Scheme, "Status": v.Status} fields := map[string]interface{}{ "UpstreamTime": v.UpstreamTime, "RequestTime": v.RequestTime, "BytesSent": v.ByteSent, }
pt, err := client.NewPoint("nginx_log", tags, fields, v.TimeLocal) if err != nil { log.Fatal(err) } bp.AddPoint(pt)
// Write the batch if err := c.Write(bp); err != nil { log.Fatal(err) }
// Close client resources if err := c.Close(); err != nil { log.Fatal(err) } fmt.Println("write success") } }
type LogProcess struct { rc chan []byte wc chan *Message read Reader write Writer }
type Message struct { TimeLocal time.Time ByteSent int Path, Method, Scheme, Status string UpstreamTime, RequestTime float64 }
// 系统状态监控 type SystemInfo struct { HandleLine int `json:"HandleLine"` // 总处理日志行数 Tps float64 `json:"tps"` // 系统吞吐量 ReadChanLen int `json:"ReadChanLen"` // read channel 长度 WriteChanLen int `json:"WriteChanLen"` // write channel 长度 RunTime string `json:"RunTime"` // 运行总时间 ErrNum int `json:"ErrNum"` // 错误数 }
const ( TypeHandleLine = 0 TypeErrNum = 1 ) var TypeMonitorChan = make(chan int, 200)
type Monitor struct { startTime time.Time data SystemInfo tpsSli []int }
func (m *Monitor) start(lp *LogProcess) { // 消费数据 go func() { for n := range TypeMonitorChan { switch n { case TypeErrNum: m.data.ErrNum += 1 case TypeHandleLine: m.data.HandleLine += 1 } } }()
ticker := time.NewTicker(time.Second * 5) go func() { for { <-ticker.C m.tpsSli = append(m.tpsSli, m.data.HandleLine) if len(m.tpsSli) > 2 { m.tpsSli = m.tpsSli[1:] } } }()
http.HandleFunc("/monitor", func(writer http.ResponseWriter, request *http.Request) { m.data.RunTime = time.Now().Sub(m.startTime).String() m.data.WriteChanLen = len(lp.wc) m.data.ReadChanLen = len(lp.rc)
if len(m.tpsSli) >= 2 { m.data.Tps = float64(m.tpsSli[1] - m.tpsSli[0]) / 5 }
ret, _ := json.MarshalIndent(m.data,"","\t") io.WriteString(writer, string(ret)) }) http.ListenAndServe(":9193", nil) }
func (l *LogProcess) Process() { // 解析模块 // 172.0.0.12 - - [04/Mar/2018:13:49:52 +0000] http "GET /foo?query=t HTTP:1.0" 200 2133 "-" "KeepAliveClient" "-" 1.005 1.854
r := regexp.MustCompile(`([\d\.]+)\s+([^ \[]+)\s+([^ \[]+)\s+\[([^\]]+)\]\s+([a-z]+)\s+\"([^"]+)\"\s+(\d{3})\s+(\d+)\s+\"([^"]+)\"\s+\"(.*?)\"\s+\"([\d\.-]+)\"\s+([\d\.-]+)\s+([\d\.-]+)`) loc , _ := time.LoadLocation("Asia/Shanghai")
// 1. 从Read Channel中读取每行日志数据 for v := range l.rc {
// 2. 正则提取所需的监控数据(path,status,method等) ret := r.FindStringSubmatch(string(v)) if len(ret) != 14 { TypeMonitorChan <- TypeErrNum log.Println("FindStringSubmatch failed : ", string(v)) continue }
message := &Message{} t, err := time.ParseInLocation("02/Jan/2006:15:04:05 +0000", ret[4], loc) if err != nil { TypeMonitorChan <- TypeErrNum log.Println("ParseInLocation failed : ", err.Error(), ret[4]) continue } message.TimeLocal = t
byteSent, _ := strconv.Atoi(ret[8]) message.ByteSent = byteSent
reqSli := strings.Split(ret[6]," ") if len(reqSli) != 3 { TypeMonitorChan <- TypeErrNum log.Println("string.Split failed : ", ret[6]) continue } message.Method = reqSli[0] u, err := url.Parse(reqSli[1]) if err != nil { TypeMonitorChan <- TypeErrNum log.Println("url parse failed : ", err) continue } message.Path = u.Path
message.Scheme = ret[5] message.Status = ret[7]
upstreamTime, err := strconv.ParseFloat(ret[12],64) message.UpstreamTime = upstreamTime
requestTime, err := strconv.ParseFloat(ret[13], 64) message.RequestTime = requestTime
// 3. 写入Write Channel l.wc <- message } }
func main() {
var path, influxDsn string flag.StringVar(&path, "path", "/tmp/access.log", "read file path") flag.StringVar(&influxDsn, "influxDsn", "http://127.0.0.1:8086@imooc@imoocpass@nginx@s", "influx data source") flag.Parse()
r := &ReadFromFile{ path: path, }
w := &WriteToInfluxDB{ influxDBDsn: influxDsn, }
lp := LogProcess{ rc : make(chan []byte), wc : make(chan *Message), read: r, write: w, }
go lp.read.Read(lp.rc) go lp.Process() go lp.write.Write(lp.wc)
m := &Monitor{ startTime: time.Now(), data: SystemInfo{}, } m.start(&lp)
//time.Sleep(6000 * time.Second) }
|