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

logger.infoを使ったログの出力方法

Posted at

1.はじめに

  • 開発中のrailsアプリにOpenWeatherAPIを使用して天気情報を取得して表示させるように変更を加えました。
  • デプロイしたところ、開発環境では正常に動いていたのに、本番環境では動かないエラーが発生。
  • 本番環境でデータ取得ができているかを確認したかったのでlogger.debugを使用して確認したので記録として残します。
  • 結論、render側でAPIの設定をしていなかったことが原因でした。

2.環境

Ruby (2.6.4)
Ruby on Rails (6.1.7)

3.解決までにおこなったこと

1.ログを確認してみる

  • 開発環境では動いていたのでAPIの取得がうまくいっていない可能性があると仮定
ActionView::Template::Error (undefined method `group_by' for nil:NilClass):
46:         <p id="text"><%= @post.text %></p>
47:         <% if @weather_data.present? %>
48:         <h2>5日間の天気予報</h2>
49:         <% daily_forecasts = @weather_data['list'].group_by { |forecast| Time.at(forecast['dt']).strftime('%Y-%m-%d') } %>
50:         <div class="daily-forecasts-container">
51:           <% daily_forecasts.each do |date, forecasts| %>
52:           <div class="daily-forecast">

2.logger.infoを使用して変数に値が入っているか確認

  • logger.(ログレベルの名称)の引数にメッセージを渡すことで、そのログレベルを持ったメッセージを保存することができる。
  • ログレベルについて
    Railsのログには5段階のレベルがある
    ログレベルは情報の必要度が低→高の順で、0→5の数値が充てられている。
ログレベル 名称 内容
0 debug デバッグ情報など
1 info 一般的な情報
2 warn 警告
3 error 制御可能なエラー
4 fatal プログラムをクラッシュさせるような制御不可能なエラー
5 unknown 常に記録されるべき不明なエラー
  def post_params
    params.require(:post).permit(:location, :text, :address, :latitude, :longitude, post_images_images: []).merge(user_id: current_user.id)
  end

  def get_weather_forecast(latitude, longitude)
    api_key = ENV['OPENWEATHERMAP_API_KEY']
+    logger.info "api_key: #{api_key}"

    api_url = "https://api.openweathermap.org/data/2.5/forecast?lat=#{latitude}&lon=#{longitude}&appid=#{api_key}&lang=ja&units=metric"
+    logger.info "api_url: #{api_url}"

    response = HTTParty.get(api_url)
+    logger.info "response: #{response}"

    weather_data = JSON.parse(response.body)

    return weather_data
  end

3.再度ログを確認

INFO -- : [914703b7-ba17-4260-95d0-d2e4c12596e7] api_key: 
INFO -- : [914703b7-ba17-4260-95d0-d2e4c12596e7] api_url: https://api.openweathermap.org/data/2.5/forecast?lat=32.8968001&lon=131.0053301&appid=&lang=ja&units=metric
INFO -- : [914703b7-ba17-4260-95d0-d2e4c12596e7] response: {"cod":401, "message": "Invalid API key. Please see https://openweathermap.org/faq#error401 for more info."}

ログをみるとapi_keyに値が入っていないことが確認でき、この時点でrender側でAPIの設定をしていないことがわかり解決

4.終わりに

今まで開発環境ではbinding.pryを使用していたが、本番環境ではlogger.infoを使用することでユーザー側での操作に影響を与えずアプリのデバッグを行えるので便利

5.おまけ

  • デフォルトのログ出力レベルを変更する
    config/environments/production.rb等でconfig.log_levelを指定することにより、環境ごとに表示するログレベルを変更できる。
    development環境、production環境,test環境それぞれに設定をすることができる。
config/environments/production.rb
# この場合だと本番環境ではログレベルがinfo以上のみ表示される
  config.log_level = :info

参考資料

Railsのログを理解する-ログの基礎知識

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?