3
2

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 1 year has passed since last update.

JSON形式のログを加工してみる

Posted at

#JSONのログを加工してみます

下記のようなログを

[
    {
        "hoge": {
        "abc" : "除外される",
        "xyz" : "除外される",
        "jjj" : "残る値"
        },
        "fuga" : "残る値",
        "fuge" : "残る値"

    },
    {
        "hoge": {
        "abc" : "除外される",
        "xyz" : "除外される",
        "yyy" : "残る値2"
        },
        "fuga" : "残る値2",
        "fuge" : "残る値2",
        "fugeex" : "除外される"

    }
]

こんな感じで加工しみたいと思います

[
    {
        "fuga": "残る値2",
        "fuge": "残る値2",
        "hoge": {
            "yyy": "残る値2"
        }
    },
    {
        "fuga": "残る値",
        "fuge": "残る値",
        "hoge": {
            "jjj": "残る値"
        }
    }
]

加工するためのソース

#! /usr/bin/env elixir

Mix.install([{:jason, "~> 1.2"}])

defmodule JFilter do
  def remove(data, path) do
    data
    |> Enum.map(&pop_in(&1, path))
    |> Enum.map(&elem(&1, 1))
  end
end

data =
  File.read!("log.json")
  |> Jason.decode!()
  |> Enum.reverse()
  |> Enum.map(&Map.take(&1, ["hoge", "fuga", "fuge"]))
  |> JFilter.remove(["hoge", "abc"])
  |> JFilter.remove(["hoge", "xyz"])
  |> Jason.encode!()

File.write!("out.json", data)

① File.read!("log.json")でログファイル読み込み
② Jason.decode!()でjsonをelixirで扱える形式に変換
③ Enum.reverse()配列を逆転
④ Enum.map(&Map.take(&1, ["hoge", "fuga", "fuge"])) 欲しい項目を選択
  この例だと hoge、fuga、fugeの3つの項目を選択
⑤ Filter.remove(["hoge", "abc"]) 除外項目を選択
  この例だと、 hogeの下にあるabcを除外
⑥ Jason.encode!() Json形式に変換
⑦ File.write!("out.json", data) ファイル出力

#おまけ

GCPのログを取得コマンド
下記の用にGCPのログを log.jsonに保存して上記のelixirで作ったスクリプトを流すとログ解析が少しは幸せに?なるかも。

gcloud logging read 'ログクエリ' --freshness="1m" --format=json  > /log.json
3
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?