0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Grafanaの描くグラフ画像に手っ取り早くタイムスタンプを入れる

Posted at

GrafanaにはImage renderingという、指定したパネルをPNG画像として取り出す機能があります。

image.png
やり方そのものは簡単で、Share PanelにあるDirect link rendered imageを叩くだけ。セッションがあるブラウザで叩いてもいいし、API TokenをBearer tokenとしcURLで叩いてもいい。

グラフ例

こんな感じで、パネルに描かれたグラフを画像として取ってこれます。

本題

Image renderingには画像を生成した時刻を描き込む機能がありません。画像に生成時間がないので、保存した画像が何時のやつかがわからない。

Image renderingがPuppeteerで指定したグラフを描画して保存する仕掛けなので、Grafanaに表示されてない情報を入れることは考えてなさそう。

選択肢はいくつかあって

  • ImageMagickでがんばる
  • Grafanaを改造する

ぐらいが思いつくのですがどちらも面倒。で、Grafanaのドキュメントを読み漁ってみたところ、取り敢えずの解をみつけたので書いておきます。

パネルタイトルにタイムスタンプを入れる

Grafanaのパネルタイトルには変数が使えます。

Panel titles and metric queries can refer to variables using two different syntaxes:
https://grafana.com/docs/grafana/latest/variables/syntax/

で、ここで使える変数にはグラフの開始および終了時刻がある。

Grafana has two built in time range variables: $__from and $__to.
https://grafana.com/docs/grafana/latest/variables/variable-types/global-variables/#__from-and-__to

Image renderingさせるパネルの表示幅が「現在から過去n時間まで」だったら、$__toは現在時刻を表すことになります1

また、$__to:date:(フォーマット文字列)でよろしく時刻をフォーマットできるとあるので、ロケール依存2ですがLLLLがわかりやすそうなので、これを含んだ文字列をパネルタイトルに設定。

image.png

パネルタイトルの変数は最初に表示された時点から更新されないのでブラウザで表示しっぱなしだと無意味なんですが、Image renderingする場合は一度表示したらブラウザ(Headless Chrome)ごと捨てるので問題がない。

image.png

これで、Direct link rendered imageで取れる画像に描画時刻を入れることができました。

  1. この前提が満たされないときは、今回書いた技は使えない。「取り敢えずの解」って書いたのはこのへん。

  2. ブラウザで叩くとユーザが設定したロケールですが、API Keyだと設定のrendering_languageが参照されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?