Go 實現 nginx log 讀取 分析 寫入InfluxDB 並用Grafana 顯示

Frank範發表於2018-05-01

參考:慕課網https://www.imooc.com/learn/982

1. 系統結構

用Go實現檔案讀取,並且將log 分析並寫入InfluxDB,最後用通過配置Grafana 顯示

log file –>log process –> influxdb –> grafana

監控需求:某個協議下的某個請求在某個請求方法的QPS和響應時間和流量

2. Go 接收

  1. Go 併發執行
    • 將複雜的任務拆分,通過goroutine去併發的執行
    • 通過channel做資料通訊
  2. Golang 中物件導向
    1. struct物件
    2. interface
    3. 封裝,繼承,多型

封裝:

type Foo struct {
    baz string
}
func (f * Foo) echo() {
    fmt.Println(f.baz)
}

繼承:

type Foo struct {
    baz string
}
type Bar strct {
    Foo
}

Code 實現:https://github.com/itsmikej/imooc_logprocess, 通過看視訊教程,應該可以能夠很好的理解code, 以及理解如何一步步實現模組封裝。

3. InfluxDB

是一個開源的時序性的資料庫,使用GO編寫,被廣泛用於儲存系統的監控資料,IOT行業的實時資料等場景,有以下特性:

- 部署簡單,無外部依賴
- 內建http支援,使用http讀寫
- 類sql的靈活查詢(max,min,sum等)

概念:database: 資料庫;measurement: 資料庫的表,points: 表裡的一行資料(tags: 有索引的屬性,fields:各種記錄的值,time: 時間戳)

寫入資料:

curl -i -XPOST 'http://localhost:8086/write?db=mydb' --data-binary 'cpu_usage,host=server01,region=us-west value=0.64 143405230000000'

讀取資料:

curl -G 'http://localhost:8086/query?pretty=true' --data-urlencode "db=mydb" --data-urlencode "q=SELECT\"value\"FROM\"cpu_usage\"WHERE "region\"='us-west'"

針對本log 系統:
tags: path, method, scheme, status
Fileds: UpstreamTime, Requestime,BytesSent
Time: Timelocal

安裝:

  1. docker pull influxdb
  2. 建立DB, curl -G http://localhost:8086/query --data-urlencode "q=CREATE DATABASE imooc"
  3. 建立使用者, curl "http://localhost:8086/query" --data-urlencode "q=CREATE USER imooc WITH PASSWORD 'imoocpass' WITH ALL PRIVILEGES"
  4. 啟動container:
docker run -itd -p 8086:8086 -v $PWD:/var/lib/influxd influxdb

4. Grafana

Grafana 可以整合多種資料來源, ES, Mysql 等 可以通過建立漂亮的GUI,實時的顯示資料。只需要配置下Datastore,以及DashBoad
安裝

docker run -d --name=grafana -p 3000:3000 grafana/grafana

Add datastore: 新增 influxdb 的地址,資料庫等資訊。

相關文章