3
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.

ElixirとCloudPub/Subを使ってStackdriverのログを取得してみる

Posted at

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書くお仕事したいっすねぇ...

3
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
3
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?