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

Railsのloggerでログの出し方

Posted at

やりたいこと

今まで色々なデバッグの多くをputs(p)で、やってました...
なので、loggerの使い方をマスターしよう編です💪

loggerの使い方

Railsでloggerを使う方法について話していきます。
基本的な使い方
Rails アプリケーション内でログを出力するにはRails.loggerがいいらしい。以下のことができるので..

実行時に情報をログに保存できるとさらに便利です。Railsは実行環境ごとに異なるログファイルを出力するようになっています。

デバッグメッセージを出力したい場合は次のように書きます。

Rails.logger.debug "This is a debug message"
Rails.logger.info "This is an info message"
Rails.logger.warn "This is a warning message"
Rails.logger.error "This is an error message"
Rails.logger.fatal "This is a fatal message"

debug,infoなどはログメソッドです。
これらのログメソッドは、以下のログレベルに対応してます。

  • debug:最も詳細なログ。開発中のデバッグに使用。
  • info:一般的な情報(例:アプリケーションが正常に動作している時の情報)。
  • warn:警告(例:非致命的な問題)。
  • error:エラー(例:処理が失敗した時)。
  • fatal:致命的なエラー(例:アプリケーションがクラッシュするようなエラー)。

ログの出力先
Rails.logger によるログは、通常は以下のいずれかに出力されます

  • ファイル出力: Rails では、デフォルトでログファイルが log フォルダに出力されます。例えば、devlopment環境では log/development.log にログが出力されます。(環境によって出力されるファイルが違います)
  • 標準出力: ターミナルにログを出力したい場合、config/application.rbconfig.logger = Logger.new(STDOUT) を設定することができます。

おまけ

config.logger = Log4r::Logger.new("Application Log")
こんなのがあるみたい。

config.logger = Logger.new(STDOUT) との違いは...

特徴 Logger.new(STDOUT) Log4r::Logger.new("Application Log")
ライブラリ Ruby標準のLogger Log4r(外部ライブラリ)
設定の柔軟さ シンプル 高度な設定が可能
出力先 標準出力(ターミナル) 任意の出力先(ファイル、コンソール、メールなど)

参考

Railsガイド ロガー

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