Logging helps you keep track of what your app is doing. Monitoring watches your app's health and alerts you if something goes wrong.
0
0
Logging and monitoring in Ruby on Rails
Introduction
You want to see errors happening in your Rails app.
You need to check how long requests take to process.
You want to know if your app is running smoothly over time.
You want to get alerts if the app crashes or slows down.
You want to keep records for debugging or audits.
Syntax
Ruby on Rails
Rails.logger.level = Logger::INFO Rails.logger.info "Your message here" Rails.logger.error "Error message here"
Rails.logger is the built-in logger in Rails apps.
You can set the log level to control what messages are saved (DEBUG, INFO, WARN, ERROR, FATAL).
Examples
Different log levels show different importance of messages.
Ruby on Rails
Rails.logger.debug "Debugging info" Rails.logger.info "App started" Rails.logger.warn "This might be a problem" Rails.logger.error "Something went wrong"
Setting log level to ERROR means only error messages are saved.
Ruby on Rails
Rails.logger.level = Logger::ERROR Rails.logger.info "This will NOT be logged" Rails.logger.error "This will be logged"
In config/environments/development.rb, you can set logger output and level.
Ruby on Rails
config.logger = Logger.new(STDOUT) config.log_level = :debug
Sample Program
This sets the log level to info and prints logs to the console. Then it logs an info and an error message.
Ruby on Rails
# config/environments/development.rb Rails.application.configure do config.log_level = :info config.logger = Logger.new(STDOUT) end # In any controller or model Rails.logger.info "User signed in" Rails.logger.error "Failed to save record"
OutputSuccess
Important Notes
Logs usually include timestamps and severity levels automatically.
Monitoring tools like New Relic or Datadog can collect and show logs and app health.
Keep log files from growing too large by rotating them regularly.
Summary
Logging records app events and errors for later review.
Monitoring watches app health and alerts you to problems.
Rails has built-in logging you can configure easily.