Normally we can output informational messages using Ruby's puts
function. For example, to print a message when the request hits the index
action, we could simply print a message as follows.
class ArticlesController < ApplicationController
def index
puts 'displaying all articles'
@title = 'All Articles'
end
end
It outputs the message which by default prints to the standard output, that is, the terminal. However, in production, the log messages will be lost, as we're not saving them anywhere. Hence, we need a flexible solution that can customize the log endpoints based on the environment.
To get started with logging, we'll use Ruby's logger standard library. Specifically, we'll use the Logger
class. From the docs,
Class Logger provides a simple but sophisticated logging utility that you can use to create one or more event logs for your program. Each such log contains a chronological sequence of entries that provides a record of the program’s activities.
Let's create a Ruby script called main.rb
with the following code in it.
require 'logger'
logger = Logger.new($stdout)
logger.info 'user logged in'
logger.error 'could not connect to the database'
After requiring the logger
library, we create a new instance of the Logger
class, passing the $stdout
global variable, which represents the current standard output.
By default,
STDOUT
(the standard output / console) is the default value for the$stdout
global variable, so the above code simply logs the messages to the console.
Let's verify by running the program.
$ ruby main.rb
I, [2023-07-29T15:04:20.155996 #36605] INFO -- : user logged in
E, [2023-07-29T15:04:20.156055 #36605] ERROR -- : could not connect to the database
As you can see, the logger printed the messages to the console, but it just didn't print the messages, but also additional information like the timestamp and the type (or severity level) of the message (INFO
or ERROR
). This lets you easily search the messages.
Instead of logging to the terminal, you may want to log it to a log file, which is a text file containing the log messages. The benefit being, you could store and archive this file for later usage or a better visibility into your application.
Let's see how you could write logs to a log file.