1. 程式人生 > 實用技巧 >記一次在Grafana中使用Worldmap Panel的經歷

記一次在Grafana中使用Worldmap Panel的經歷

背景

因與工作相關,以下內容皆做了脫敏處理

主要的需求是要根據地理位置檢視視覺化的資料。

安裝及建立

安裝命令來源於官網

grafana-cli plugins install grafana-worldmap-panel

安裝成功後建立

通過ip獲取所在地區

請見開源專案ip2region

https://github.com/lionsoul2014/ip2region

通過所在地區獲取經緯度

因為worldmap使用的是OpenStreetMap,所以需要找個能根據地區查詢經緯度的介面

以下是一個返回值示例,請求的url為:https://nominatim.openstreetmap.org/search?format=json&state=北京,返回值如下:

[
{
"place_id": 235181418,
"licence": "Data OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_type": "relation",
"osm_id": 912940,
"boundingbox": [
"39.4416113",
"41.0595584",
"115.4172086",
"117.5079852"
],
"lat": "40.190632",
"lon": "116.412144",
"display_name": "北京市, 中國",
"class": "boundary",
"type": "administrative",
"importance": 0.8344014383682882,
"icon": "https://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png"
}
]

可以看到latlon欄位,分別是維度、精度。

Prometheus準備資料

因為我們Grafana中已經配置了Prometheus資料來源,所以現在提供一個Metric就可以了。

Metric的獲取邏輯如下:

  • 根據從ip查詢到的城市進行分組,並記錄他們的值。
  • 通過快取過的城市到經緯度的對映查詢對應的經緯度
  • 呼叫Prometheus的sdk提供Metric介面

介面格式如下:

userip為Metric名稱,label分別為維度、精度、名稱,值是分佈數量,在worldmap表現為圈的大小

# HELP userip 使用者IP分佈
# TYPE userip gauge
userip{latitude="40.190632",longitude="116.412144",name="北京市"} 20
userip{latitude="31.2322758",longitude="121.4692071",name="上海市"} 33

配置worldmap

Metric選項配置

指標名填寫上一步的userip,注意圈起來的地方

Worldmap選項配置

Metric Field中的ValueV是大寫,其他三個欄位分別與label對應。



儲存後就大功告成

來吧,展示!

以下為部分測試資料