Stackdriverにあるアプリケーションのログを取得してゴニョゴニョしてみたいという気持ちが出てきたので愛するElixirでそれが実現可能か試してみました。
後で見返すときの自分用備忘録です
注意.1)
この記事を読んで得られるものはここに書いてる内容(GoogleCloudPlatform/elixir-samples)と同じです!
気になる人はコードも見てみてね!
注意.2)
StackdriverからCloudPubsubへログを流す方法についてはここでは記載しません🙏
GoogleCloudPlatform/elixir-samples
Elixir向けのCloudPub/Subのサンプル実装が↑のリポジトリにある。
今回、topicの作成とかはGCPのコンソールからやってるので elixir-samples/pubsub/lib/pubsub_samples_subscriber.exにある実装を パクって 持ってきます。
# mix.exsに以下のライブラリを追加
defp deps do
[
{:google_api_pub_sub, "~> 0.23.0"},
{:goth, "~> 1.1.0"},
]
end
def listen(project_id, subscription_name) do
{:ok, token} = Goth.Token.for_scope("https://www.googleapis.com/auth/cloud-platform")
conn = GoogleApi.PubSub.V1.Connection.new(token.token)
# Make a subscription pull
{:ok, response} = GoogleApi.PubSub.V1.Api.Projects.pubsub_projects_subscriptions_pull(
conn,
project_id,
subscription_name,
[body: %GoogleApi.PubSub.V1.Model.PullRequest{
maxMessages: 10
}]
)
if response.receivedMessages != nil do
Enum.each(response.receivedMessages, fn message ->
# Acknowledge the message was received
GoogleApi.PubSub.V1.Api.Projects.pubsub_projects_subscriptions_acknowledge(
conn,
project_id,
subscription_name,
[body: %GoogleApi.PubSub.V1.Model.AcknowledgeRequest{
ackIds: [message.ackId]
}]
)
# ここに書きたい処理を書く。今回はIO.putsしてる
"received and acknowledged message: #{Base.decode64!(message.message.data)}"
|> (&IO.ANSI.format([:green, :bright, &1])).()
|> IO.puts
end)
end
listen(project_id, subscription_name)
end
これで動くよ!!
今後やりたいこと
ここではログをPullしてくるまでしかしてないですが本番ではPullしたデータを加工してBigQueryに挿入していく処理を書く予定だったりします。
ElixirはLISTを美しく処理できるのでログの中から必要なものを抽出して加工してBulkInsertするとかも綺麗に書けるんじゃないかととても期待している。
感想
Elixirいいぞぉ!
ずっとElixir書くお仕事したいっすねぇ...