🐙

【Rails】logをいい感じにしてくれるlogrageというgem

2023/05/11に公開

はじめに

ログをいい感じに出してくれるlogrageについてメモ

Gituhub

https://github.com/roidrage/lograge

設定ファイル

GituhbのREADMEとほぼ同じかもですが、参考までに。
以下は殴り書きで。

custom_payloadについて

custom_payloadについて
Alternatively, you can add a hook for accessing controller methods directly (e.g. request and current_user). This hash is merged into the log data automatically.

▼ コントローラのメソッドに直接アクセスして、パラメータとuser_idやrequest_idなどを表示させる。

    config.custom_payload do |controller|
      params = controller.request.params.except(* %w[controller action])

      {
        hostname: `hostname`,
        request_id: controller.request.request_id,
        user_id: controller.try(:current_user).try(:id),
        params: params,
      }
    end

custom_options

You can then add custom variables to the event to be used in custom_options (available via the event.payload hash, which has to be processed in custom_options method to be included in log output, see above):

The payload does already contain the params hash, so you can easily add it in manually using custom_options:

The :exception is just the basic class and message whereas the :exception_object is the actual exception instance. You can use both / either. Be mindful when including this, you will probably want to cherry-pick particular attributes and almost definitely want to join the backtrace into something without newline characters.

▼ カスタム変数をイベントに追加しつつ、エラーメッセージがあれば追加する。

    config.custom_options = lambda do |event|
      options = {
        request_ip: event.payload[:request_ip],
        options[:error_message] = event.payload[:exception_object]&.message
        options[:error_stacktrace] = event.payload[:exception_object]&.backtrace&.join("\n")
        time: Time.zone.now,
      }
    end

↑本当はぼっち演算子使わないで綺麗に書くべき。。

LogStashを使う

Lograge supports multiple output formats. The most common is the default lograge key-value format described above. Alternatively, you can also generate JSON logs in the json_event format used by Logstash.

LogStashを使ってJSON形式でもいけそう。

  # JSON(logstash形式)で出力
  config.lograge.formatter = Lograge::Formatters::Logstash.new

Discussion